I want to update the first record in the NSManagedObject
. What I have here updates all of them which I realise is because I am selecting them all and updating them all using the for but how do I just update the first record?
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
NSError *errorLoading = nil;
self.users = [context executeFetchRequest:fetchRequestNext error:& errorLoading];
for (NSManagedObject *usersObject in [self users])
{
[usersObject setValue:@"*" forKey:@"currentUser"];
}
NSError *error;
[context save:&error3];
}
Kind of like this:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
fetchRequest.fetchLimit = 1; //Fetch only one object (optional)
NSError *errorLoading = nil;
NSManagedObject *user = [[context executeFetchRequest:fetchRequestNext error:& errorLoading] firstObject];
if (errorLoading) {
//handle error
}
[user setValue:@"*" forKey:@"currentUser"];
NSError *error = nil;
if (![context save:&error]) {
//handle error
}
First of all, if you only need one object, you can set the fetchLimit
to 1. It is not required, it's just a small optimization (it will make CoreData stop after fetching the first object). Then you execute the request just like you normally would and get the first object from the resulting array.