I might have my terminology incorrect in the title using the word singleton.
I searching for a good technique now. I have an entity named user that stores a users logged in data such as a session key for making server requests. I only ever want one of these entities to exist ever. Is there a standard technique for doing this?
What I have so far is something like this
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"UserEntity" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
if ([array count]==0) {
//first run of app
}else if([array count]==1)
{
// id like the code to enter here after every app run except for the first one
}else
{
//dont want this to happen
}
I use Matt Gallagher’s approach described in his article Singletons, AppDelegates and top-level data.
It uses a macro to create a “synthesized singleton” class that you can then access from anywhere. Very handy for things like sessions, managed object contexts, etc. Otherwise you’d have to pass these round everywhere.