Sam Kirkiles
Sam Kirkiles

Reputation: 27

Having only one instance of an entity in Core Data

I am making an application where you need to log in with a 4 digit password but there can only be one password at a time. I am trying to save it to core data but whenever the user adds a new password it just adds it to the long list. How can I restrict an entity to only have one instance of itself?

Here is my code just in case it will help:

-(BOOL)savePassword:(NSString*)password{
    AppDelegate * appDelegate = [[AppDelegate alloc]init];
    NSManagedObjectContext * context = [appDelegate managedObjectContext];
    AppData * appData = (AppData*)[NSEntityDescription insertNewObjectForEntityForName:@"AppData" inManagedObjectContext:context];
    appData.password = password;
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"AppData" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"There was an error:%@",error);
    }

    for (AppData * adata in fetchedObjects) {
        NSLog(@"Password:%@",adata.password);
    }
    return YES;
}

Thanks!

Upvotes: 0

Views: 1104

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70946

The right approach here is to not put this data in Core Data. If you only have one instance, there's no point in using Core Data to solve the problem. There's no benefit to using Core Data for this. Put it somewhere else. Code solutions miss the point, because even if it works, it's a bad design.

Upvotes: 5

Adnan Aftab
Adnan Aftab

Reputation: 14477

You should do like this, first create fetch request and execute a fetch. check if object exist, update data. else if no data exist create an object and save it. If name of entity which is storing password. Your code should look like this

AppData * appData;
 NSManagedObjectContext * context = [appDelegate managedObjectContext];
 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"AppData" inManagedObjectContext:context];
 [fetchRequest setEntity:entity];

 NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
 if(fetchObjects.count > 0){
      appData = [fetchObjects objectAtIndex:0];//assume there will be one object

      // and do reset of thing
 }
  else{

       appData = (AppData*)[NSEntityDescription insertNewObjectForEntityForName:@"AppData" inManagedObjectContext:context];

 }
 appData.password = password;
 // save moc here
 [context save:nil];

Upvotes: 2

Related Questions