Creating a global objective-c class?

I want to create a class in objective-c with the data already saved, so for accessing the data I do not want to instantiate the class. How can i do this?

+4
source share
1 answer

You can use singleton mode, or you can use a class created only from class methods and giving you access to static data.

Here is the basic implementation of singleton 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 as follows:

 int a = [MySingleton sharedSingleton].prop [[MySingleton sharedSingleton] method]; 

The class is based on the class method:

 @interface MyGlobalClass : NSObject + (int)data; @end @implementation MySingleton static int data = 0; + (int)data { return data; } + (void)setData:(int)d { data = d; } @end 
+9
source

Source: https://habr.com/ru/post/1441989/


All Articles