我正在尝试学习如何使用 Core Data 和 UIManagedDocuments。首先我创建/打开文档:
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"ProjectSSBDB"];
document = [[UIManagedDocument alloc] initWithFileURL:url];
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]])
{
[document openWithCompletionHandler: ^(BOOL success)
{
if (success) [ProjectSSViewController documentIsReady];
if (!success) NSLog(@"Couldn't open document at %@", url);
}];
}
else
{
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
NSLog(@"Returned %d", success);
if (success) [ProjectSSViewController documentIsReady];
if (!success) NSLog(@"Couldn't create document at %@", url);
}];
}
然后,一旦创建并成功打开文档,我会这样做:
if (document.documentState == UIDocumentStateNormal)
{
NSManagedObjectContext *context = [document managedObjectContext];
Exercise *exercise = (Exercise *) [NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:context];
}
似乎这里的最后一行是给我错误的那个:'+entityForName: nil is not a legal NSManagedObjectContext parameter searching entity name'Exercise''
我确实创建了一个具有“练习”实体的数据模型。从我所做的阅读来看,这可能与不同线程与上下文交互的方式有关?但我不确定,任何指导都会很棒!