Singleton Entity in CoreData

I may have the wrong terminology in the title using the word singleton. Now I am looking for a good technique. I have an object called user that stores registered users, such as a session key for server requests. I just want one of these entities to ever exist. Is there a standard technique for this?

That i still have 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 } 
+6
source share
2 answers

I use the Matt Gallagher approach described in his article Singletons, AppDelegates, and Top-Level Data .

It uses a macro to create a “synthesized singleton” class, which can then be retrieved from anywhere. Very handy for things like sessions, managed object contexts, etc. Otherwise, you will have to go through these rounds everywhere.

+3
source

Your approach should work, and it can be flexible. Consider the possibility that in a future version of your application it is possible to manage multiple accounts; you can easily achieve this if you model your singleton as a regular object.

If you are 100% sure you will never want this, you can use the metadata repository property to store things like this.

+2
source

Source: https://habr.com/ru/post/888015/


All Articles