Using a singleton to create an array accessible by multiple views

后端 未结 2 791
终归单人心
终归单人心 2020-12-03 13:17

It\'s a classic problem.

I would like to access an array of objects from anywhere within my app. I would also like to do this using a singleton. My questions are:

2条回答
  •  -上瘾入骨i
    2020-12-03 13:41

    Do your singleton like this:

    @interface Singleton : NSObject
    @property (nonatomic, retain) NSMutableArray *bananas;
    +(Singleton*)singleton;
    @end
    @implementation Singleton
    @synthesize bananas;
    +(Singleton *)singleton {
        static dispatch_once_t pred;
        static Singleton *shared = nil;
        dispatch_once(&pred, ^{
            shared = [[Singleton alloc] init];
            shared.bananas = [[NSMutableArray alloc]init];
        });
        return shared;
    }
    @end
    

    The singleton is initialized the first time you use it. You can call it from anywhere at any time:

    NSLog(@"%@",[Singleton singleton].bananas);
    

提交回复
热议问题