Eric
Eric

Reputation: 4061

Edit Entity in Core Data

Is there a method similar to insertNewObjectForEntityName that edits the current entity being passed in managed object context? I don't want to create another duplicate entity.

In addition, I don't want users to be able to enter two entities with identical attributes (one attribute, the event title). How can I make it so an alert pops up when they try to add a new entity with an identical title attribute?

Upvotes: 0

Views: 806

Answers (1)

Simon Goldeen
Simon Goldeen

Reputation: 9080

Your first question it sounds like what you want to do is get an object that is already in the context with a fetch request, change some values on the object then call the -save method on your context.

For the second part, what you would do is when the user tries to add an item, search the context for an object with the same title, if the item exists, pop up an alert.


Edit: here is some code from my app (edited a bit) in which I set up and execute a fetch request:

NSFetchRequest *categoryRequest = [[NSFetchRequest alloc] init];
[categoryRequest setEntity:[NSEntityDescription entityForName:@"Category" inManagedObjectContext:[self managedObjectContext]]];
NSString *categoryName = @"Cooking";
NSPredicate *categoryNameMatchesPredicate = [NSPredicate predicateWithFormat:@"name MATCHES %@", categoryName];
[categoryRequest setPredicate:categoryNameMatchesPredicate];
NSError *error = nil;
NSArray *categoryArray = [[self managedObjectContext] executeFetchRequest:categoryRequest error:&error];

After this request, the array categoryArray contains all category entities with the name "Cooking". If there are no entities with the name "Cooking" the array will be empty.

It is probably faster to use -countForFetchRequest:error: and check for nonzero count before you actually execute the fetch request, but I am not sure it matters that much in a smallish iOS app.

Upvotes: 1

Related Questions