Singleton Entity in CoreData
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 i开发者_运维知识库f([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.
Your approach should work and it has the benefit of being flexible. Consider the possibility that a future version of your app has the ability to manage multiple accounts; you could easily achieve this if you model your "singleton" as a regular entity.
If you're 100% certain that you'd never want that, you could use the persistent store's metadata
property for things like this.
精彩评论