我的 Core Data 应用程序有两个实体:“Note”和“Marker”。Note 实体与标记具有一对多的关系(即,注释包含许多标记)。我有一个 fetchedRequestController 负责获取所有“Note”实体。创建 1 个注释和 1 个标记(属于该注释)后,我收到一个错误,因为 fetchedRequestController 获取了标记和注释。注意是预期的,但不应获取标记。
这是我获取的请求控制器
TCModel *model = [TCModel sharedModel];
NSManagedObjectContext *context = [model managedObjectContext];
NSParameterAssert(context);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:context];
NSParameterAssert(entity);
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:@"Root"];
NSParameterAssert(controller);
self.fetchedResultsController = controller;
controller.delegate = self;
NSError *error;
BOOL success = [controller performFetch:&error];
if ( success == NO )
{
NSLog(@"Failed to fetch!");
NSParameterAssert(nil);
}
使用两个辅助方法创建对象,然后使用第三个方法保存
- (TCNote *)newNote
{
TCNote *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note"
inManagedObjectContext:self.managedObjectContext];
note.creationDate = [NSDate new];
return note;
}
- (TCMarker *)newMarker
{
TCMarker *marker = [NSEntityDescription insertNewObjectForEntityForName:@"Marker"
inManagedObjectContext:self.managedObjectContext];
return marker;
}
- (void)_save
{
NSError *error;
NSLog(@"Saving");
if (![self.managedObjectContext save:&error])
{
NSLog(@"Error saving context: Error = %@", error);
}
}
这是控制台输出:
2013-01-03 17:41:12.062 时间码 [10269:c07] CoreData: sql: 从 Z_METADATA 中选择 Z_VERSION、Z_UUID、Z_PLIST
2013-01-03 17:41:12.063 时间码 [10269:c07] CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.Z_OPT, t0.ZNOTEDATE, t0.ZSCENEDESCRIPTION, t0.ZSCENETITLE, t0.ZTIMECODEDATE, t0 .ZDATE, t0.ZTITLE, t0.ZPARENT, t0.Z1_PARENT 来自 ZNOTE t0
2013-01-03 17:41:12.064 时间码[10269:c07] CoreData:注释:sql 连接获取时间:0.0005s
2013-01-03 17:41:12.064 时间码 [10269:c07] CoreData:注释:总提取执行时间:2 行 0.0011 秒。