IOS - updates a managed entity if a search is found

I just can't figure out how to update the main data object after I retrieve the object I want to change.

This is what I am trying to do:

1) Find the 1st object from the predicate conditions corresponding to the main data:

NSInteger storeId = 235; //find object with this id in core data NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; [context setPersistentStoreCoordinator:[self.managedObjectContext persistentStoreCoordinator]]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Store" inManagedObjectContext:context]; [request setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %i",storeId]; [request setPredicate:predicate]; NSArray *results = [context executeFetchRequest:request error:NULL]; 

2) If a match is found, update the corresponding object (I need help here):

 if (results != nil && [results count] > 0) { /** Not sure how to get the correct context and modify object **/ Store *matchingObject = [results objectAtIndex:0]; [context setValue:[NSNumber numberWithInteger:storeId] forKey:"id"]; } /** Save the context */ NSError *error = nil; if (![context save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); //abort(); } 

Thanks for any help you can provide ...

+4
source share
1 answer

Try changing the property of the object directly and save it:

 matchingObject.id = [NSNumber numberWithInteger:storeId]; 

The object was originally loaded using context , so you can save your changes by calling save on context .

+2
source

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


All Articles