How to keep a variable in memory until the app quits

扶醉桌前 提交于 2019-12-04 14:37:11
+(MySingleton *)singleton {
    static dispatch_once_t pred;
    static MySingleton *shared = nil;
    dispatch_once(&pred, ^{
        shared = [[MySingleton alloc] init];
        shared.someVar = someValue; // if you want to initialize an ivar
    });
    return shared;
}

From anywhere:

NSLog(@"%@",[MySingleton singleton].someVar);

Note that your iOS app already has a singleton that you can access anywhere:

AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

a simple singleton would be something like... in the .h:

@interface Foo : NSObject

+ (Foo *)sharedInstance;

@end

and in the .m:

static Foo *_foo = nil;

@implementation Foo

+ (Foo *)sharedInstance {
  if (!_foo)
    _foo = [[Foo alloc] init];
  return _foo;
}

@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!