Reputation: 115
If I create an instance of singleton class in MyViewController, how then to call singleton from MyViewController? Like class method or like instance?
Upvotes: 0
Views: 81
Reputation: 116
To create a singleton in objective-C you need to to this:
@interface gaSharedData : NSObject
+ (gaSharedData *)sharedInstance;
@end
in the .h file of the singleton class. In the .m file you need:
static gaSharedData *sharedObject = nil;
+ (gaSharedData *)sharedInstance
{
static dispatch_once_t _singletonPredicate;
dispatch_once(&_singletonPredicate, ^{
sharedObject = [[self alloc] init];
});
return sharedObject;
}
- (id)init {
return self;
}
Now if you want to get an instance of the class gaSharedData, you need to call this like that:
gaSharedData *data = [gaSharedData sharedInstance];
I hope this helps you :)
Upvotes: 2