1
votes

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?

1
I found that it works when I used only the save section of the code. I think it is because theBook is also a result of fetch. - glast
your question is not clear at all. and I cannot see why it will not work. - Bryan Chen
When I treat the core data as a database, I thought that I should (1) get an object from the fetch request and (2) edit the object's value and (3) then save. But it works when I omit the process (1) and (2). I'm not a native english user so it's hard to explain my question. Sorry :) - glast
still not clear for me. you did fetch object from CoreData and process 2 is optional. - Bryan Chen
why it is not optional.... of cause you don't have to update the database and it will not break - Bryan Chen

1 Answers

1
votes

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.