我在创建它之后尝试打开NSManagedDocument
。几次成功打开文档后似乎无法打开文档。如果我更改文档名称或再次删除/复制应用程序,它可以工作。每次应用程序启动时,都会在app委托中调用以下方法。
-(void) loadDataDocument {
NSURL *documentURL= [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"TestDataDocument1"];
self.document = [[UIManagedDocument alloc] initWithFileURL:documentURL];
if(![[NSFileManager defaultManager] fileExistsAtPath:[documentURL path]]) {
[self.document saveToURL:documentURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
[self documentIsReady];
}else {
NSLog(@"Tried to create new file. Cannot open document");
}
}];
} else if (self.document.documentState == UIDocumentStateClosed) {
[self.document openWithCompletionHandler:^(BOOL success) {
if (success) {
[self documentIsReady];
}else {
NSLog(@"Document was Closed. Cannot open document");
}
}];
} else {
[self documentIsReady];
}
}
答案 0 :(得分:0)
-(void) loadDataDocument {
NSString * fileUrl = [NSString stringWithFormat:@"%@abc.txt",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]];
NSURL *documentURL= [NSURL URLWithString:fileUrl];
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:documentURL];
if(![[NSFileManager defaultManager] fileExistsAtPath:[documentURL path]]) {
[document saveToURL:documentURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSManagedObjectContext * _context;
_context = document.managedObjectContext;
}
}];
} else if (document.documentState == UIDocumentStateClosed) {
NSLog(@"document.documentState == UIDocumentStateClosed");
NSString *fileDataStr = [[NSString alloc]initWithContentsOfURL:documentURL encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",fileDataStr);
} else {
NSManagedObjectContext * _context;
_context = document.managedObjectContext;
}
}
注意:强> 'UIManagedDocument只能读取文件包'
的文档