我正在遵循standford在线ios课程来测试核心数据的基础知识,而我只是在简单地保存数据时遇到了困难。现在,我有下面的代码块,输出"文件不存在" ...意味着它永远不会进入我创建上下文并保存数据的块。为什么说该文件不存在?请帮忙,我是一个noobie。
NSString * text = self.userTextField.text;
//save this text
NSLog(@"entered button function");
NSFileManager* fileManager = [NSFileManager defaultManager];
NSURL* docDir = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @"myDoc";
NSURL* url = [docDir URLByAppendingPathComponent:documentName];
UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];
if (fileExists)
{
[doc openWithCompletionHandler: ^(BOOL success) {
if (doc.documentState == UIDocumentStateNormal){
NSManagedObjectContext *context = doc.managedObjectContext;
TallyEntry* entry1 = [NSEntityDescription insertNewObjectForEntityForName:@"TallyEntry" inManagedObjectContext:context];
entry1.name = text;
NSLog(@"entry1 saved");
}
else
NSLog(@"not ready");
}];
}
else
NSLog(@"file does not exist");
我也尝试删除整个Bool fileExists部分并运行:
if (doc.documentState == UIDocumentStateNormal){
NSManagedObjectContext *context = doc.managedObjectContext;
TallyEntry* entry1 = [NSEntityDescription insertNewObjectForEntityForName:@"TallyEntry" inManagedObjectContext:context];
entry1.name = text;
NSLog(@"entry1 saved");
}
else
NSLog(@"not ready");
}];
但是这不起作用,并且它不断输出"没有准备好......这意味着文档不处于正常状态。我该如何改变?