My question is the following: I have a singleton type object (I'm using ARC) that has this code in the implementation file
+(id)sharedInstance
{
static DataManager *sharedInstance;
if (sharedInstance == nil) {
sharedInstance = [[DataManager alloc] init];
}
return sharedInstance;
}
+(NSManagedObjectContext *)getManagedContext
{
AppDelegate *applicationDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
return [applicationDelegate managedObjectContext];
}
+(void)saveContext:(NSManagedObjectContext *)context
{
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
#pragma mark - Data management methods
+(void)addPersonWithName:(NSString *)name andPicture:(UIImage *)picture
{
NSManagedObjectContext *context = [self getManagedContext]; //no problem here
//some code
[self saveContex:context]; // no known class method for selector saveContext:
}
Why is that? The method is declared in the .h file with + ... the getManagedContext
model doesn't give this error????
The keyword self inside a method references the owner of the method, which is the instance of the object for instance methods, and the class for class methods. However, the message
saveContex
is missing a t at the end (saveContext
).dispatch_once singleton
And here is a better singleton idiom compatible with ARC:
Same code as Xcode template
Same code as a Xcode template with placeholders:
Same code + disabled alloc/init/new
Want to clue users that they should call
sharedInstance
instead alloc/init/new? You can disable methods with attribute unavailable. This will cause a compiler error if any of those methods is called on the class.Warning: dispatch_once is not reentrant
Don't make a recursive call to
sharedInstance
from inside thedispatch_once
block.If you call
dispatch_once
from several threads it will act as a barrier preventing concurrent access. But if you call it again in the same thread from inside the block it will deadlock the thread. This example illustrates the problem:+initialize singleton
Using +initialize is an alternative idiom to create a singleton. Pros: It is several times faster than
dispatch_once
. Cons:+initialize
is called once per class, so if you subclass the singleton, an instance will be created for each parent class too. Use it only if you know the singleton will not be subclassed.