I am very new to Objective C and stumbled upon this problem. How is it possible to create a global instance of a class in Objective C which is accessible from multiple classes and the main function?
Asked
Active
Viewed 940 times
1
-
1possible duplicate of [objective-c - global variables](http://stackoverflow.com/questions/8808159/objective-c-global-variables) – edtheprogrammerguy Jul 04 '14 at 16:39
-
Duplicate of http://stackoverflow.com/questions/8808159/objective-c-global-variables – edtheprogrammerguy Jul 04 '14 at 16:39
-
@dasblinkenlight that one is not thread-safe. The current recommended method is to use `dispatch_once`, otherwise you can use `@synchronized`. See http://www.galloway.me.uk/tutorials/singleton-classes/ – jcaron Jul 04 '14 at 17:02
-
@jcaron You are right - I linked an older answer. [Here is a more modern answer showing how to make a singleton](http://stackoverflow.com/a/11945106/335858). Thanks! – Sergey Kalinichenko Jul 04 '14 at 17:05
3 Answers
2
You can do it in this way:
+(MyClass *) sharedInstance
{
static id sharedInstance = nil;
@synchronized(self)
{
if (!sharedInstance)
{
sharedInstance = [[MyClass alloc] init];
}
return sharedInstance;
}
}
Just access the object by this single line of code:
[MyClass sharedInstance]
Hope it helps!! Happy Coding :)

Sahil Mahajan
- 3,922
- 2
- 29
- 43
1
Add a method to your class that returns this specific instance.
The most common case is the singleton. You can also look up "shared instance".

jcaron
- 17,302
- 6
- 32
- 46
-1
You can use singleton, import the .h file in your .pch file, by doing that every file will have this imported :
YourClass.h :
@interface YourClass : NSObject
/**
* Method to get the singleton instance
* @return Instance of YourClass
*/
+ (YourClass *)instance;
@end
YourClass.m :
#import "YourClass.h"
@interface YourClass(){
}
@end
#pragma mark -
@implementation YourClass
- (id)init{
//prevents normal inits
return nil;
}
+ (YourClass *)instance
{
static YourClass *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] initSingelton];
});
return instance;
}
- (id)initSingelton{
if (self = [super init]) {
//do stuff here
return self;
}
return nil;
}

Moti F.
- 142
- 3