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:
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);