user3196922
user3196922

Reputation: 115

How to call singleton here? ios7

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

Answers (1)

Uwe Gropengießer
Uwe Gropengießer

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

Related Questions