Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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
    }
like image 895
dubbeat Avatar asked May 13 '11 09:05

dubbeat


2 Answers

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.

like image 143
Max MacLeod Avatar answered Oct 13 '22 15:10

Max MacLeod


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.

like image 30
omz Avatar answered Oct 13 '22 16:10

omz