3

我试图NSManagedDocument在创建它之后打开它。成功打开文件几次后似乎无法打开文件。如果我更改文档名称或再次删除/复制应用程序,它可以工作。每次应用程序启动时,都会在应用程序委托中调用以下方法。

-(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];
    }

}

4

1 回答 1

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 只能读取文件包的文档'

于 2013-03-27T20:00:19.577 回答