Reputation: 383
I am confused of the core data's logic.
I treated the core data as a database, and core data methods as a SQL query.
When I tried to update some object in a core data with a local memory's object, I found that I can make the feature just with below code:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Book" inManagedObjectContext:_managedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"identifier == %@", theBook.identifier];
[request setPredicate:predicate];
NSError *error;
Book *book = [[_managedObjectContext executeFetchRequest:request error:&error] lastObject];
if (error) {
NSLog(@"Error getting book to update: %@", error);
abort();
}
// NSLog(@"%d", book == theBook);
error = nil;
if (![_managedObjectContext save:&error]) {
NSLog(@"Error saving the book: %@", error);
abort();
}
theBook
is the object which I want to update the core data's object with.
And I found that the log message says the two objects are same...
I fetched the request and didn't do anything but it works. Why does it work?
Upvotes: 1
Views: 93
Reputation: 6032
At first Core Data is not a database - it's an object graph, which could be saved to some kind of storage.
If your objects in there have unique identifier
, then fetching with the same identifier
value gives you the same object. Core Data does not create different instances of managed objects for the same entities (say book with identifier=7), so everywhere you'll deal with the same object, doesn't matter if you fetch it 15 times, you'll always end up with the same one.
Upvotes: 1