0

我的 iOS 应用程序中的 Core Data 有问题。

首先,我的 ManagedObject 的代码:

@interface MyBook : NSManagedObject
  @property (retain, nonatomic) NSString *book_name;
@end


@implementation MyBook    
  @synthesize book_name;
@end

和代码示例:

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);

代码基本上...

  • 尝试按名称查找一本书并抓住它。
  • 如果该书尚不存在,请创建一个并设置书名。
    • 否则,抓住现有的书。

我遇到的奇怪事情是,当这本书已经存在时,该属性book_name为空。如果创建了对象,book_name将具有我之前设置的字符串。

我猜对属性的访问不会导致获取的书籍实例出现故障。这可能是[book valueForKey:@"book_name"]有效的原因,之后该属性也已被填充。

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

4

1 回答 1

2

Big WHOOPS!

Just after posting this original question, I realized that I was using @synthesize instead of @dynamic.

However, I'll leave this question here, if anyone else experiences such an effect in the future. :)

于 2012-09-16T12:32:44.693 回答