Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a global class objective-c?

I want to create a class in objective-c with already stored data, so that for accessing the data I don't want to instantiate the class. how can I do it?

like image 599
Sikander Avatar asked Jan 15 '23 05:01

Sikander


1 Answers

You can use a singleton or you can use a class made only of class methods and giving you access to static data.

Here is a basic singleton implementation in ObjC:

@interface MySingleton : NSObject
{
}

+ (MySingleton *)sharedSingleton;

@property(nonatomic) int prop;
-(void)method;

@end

@implementation MySingleton
@synthesize prop;

+ (MySingleton *)sharedSingleton
{ 
  static MySingleton *sharedSingleton;

  @synchronized(self)
  {
    if (!sharedSingleton)
      sharedSingleton = [[MySingleton alloc] init];

    return sharedSingleton;
  }
}

-(void)method {

}

@end

and you use it like this:

int a = [MySingleton sharedSingleton].prop

[[MySingleton sharedSingleton] method];

The class method based class would be:

@interface MyGlobalClass : NSObject

+ (int)data;

@end

@implementation MySingleton

static int data = 0;
+ (int)data
{ 
   return data;
}

+ (void)setData:(int)d
{ 
   data = d;
}

@end
like image 193
sergio Avatar answered Jan 25 '23 10:01

sergio