给定一个删除了布尔属性的 NSManagedObject 子类(这在下面的代码中以两种不同的方式演示,因为这两种方法都不起作用):
[代码清单 1]
@interface MyManagedObject : NSManagedObject
@property (nonatomic, retain) NSNumber *deleted;
// Or @property (nonatomic) BOOL deleted;
@end
创建并插入核心数据如下:
[代码清单 2]
metadata.deleted = [NSNumber numberWithBool:NO];
// metadata.deleted = NO;
并取得
[代码清单 3]
// setup entity description
NSEntityDescription* entityDescription = [self entityDescription];
// setup the sorter
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:YES];
NSSortDescriptor* sortDescriptorSection = [[NSSortDescriptor alloc] initWithKey:@"myManagedObject.category.title" ascending:YES];
// Build request
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptorSection, sortDescriptor, nil]];
[request setPredicate:[NSPredicate predicateWithFormat:@"deleted == %@", [NSNumber numberWithBool:NO]]];
// Fetch request
NSArray* items = [[self managedObjectContext] executeFetchRequest:request error:nil];
按预期返回 items 数组中的一项。问题是当删除被修改时:
[代码清单 4]
MyManagedObject* myManagedObject; // Assume initialized
myManagedObject.deleted = [NSNumber numberWithBool:YES];
// myManagedObject.deleted = YES;
// Printing description of myManagedObject in debugger shows deleted = 0 at this point
[myManagedObject.managedObjectContext save:nil];
// Printing description of myManagedObject in debugger still shows deleted = 0 at this point
BOOL testValue = myManagedObject.deleted;
if (testValue) {
NSLog(@"value updated"); // This line is executed
}
即使在监视数据库的 NSFetchResultsController 触发了更新之后,重新执行代码清单 3 仍会在 items 数组中产生一项。如果应用程序终止并重新启动,则重新执行代码清单 3 不会在 items NSArray 中产生任何项目。