I have a problem with Core Data in my iOS app.
First off, the code for my ManagedObject:
@interface MyBook : NSManagedObject
@property (retain, nonatomic) NSString *book_name;
@end
@implementation MyBook
@synthesize book_name;
@end
And the code sample:
NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"MyBook"];
fr.predicate = [NSPredicate predicateWithFormat:@"book_name == %@", @"Something"];
NSArray *result = [s.managedObjectContext executeFetchRequest:fr error:&error];
MyBook *book = nil;
if (result.count) {
book = [result objectAtIndex:0];
NSLog(@"Updating old book: %@", book);
} else {
book = [NSEntityDescription insertNewObjectForEntityForName:@"Book"
inManagedObjectContext:s.managedObjectContext];
NSLog(@"Creating new book");
shelf.book_name = // some unique book name is set here
}
NSLog(@"result: %@", book.book_name);
The code basically...
- Tries to look up a book by name and grab that.
- If the book does not exist yet, create one and set the book name.
- Otherwise, grab the existing book.
The weird thing I'm experiencing is that when the book already exists, the property book_name
is null. If the object was created, book_name
will have the string I set before.
I guess access to the property is not causing a faulting on the fetched book instance. That's probably why [book valueForKey:@"book_name"]
works and after that the property has been populated as well.
What am I missing here? I'm expecting Core Data to notice that I'm accessing the property and internally grabbing the data for me transparently.
Thank you