3

在我的 iPhone 应用程序中,我需要将二进制数据附加到文件中:

 NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSData* data = [NSData dataWithBytes:buffer length:readBytes_];    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
    [myHandle seekToEndOfFile];
    [myHandle writeData: data];
    [myHandle closeFile];
   // [data writeToFile:appFile atomically:YES];

    // Show contents of Documents directory
    NSLog(@"Documents directory: %@",
          [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

但是在 NSlog 中我看不到有我的文件。怎么了?

4

1 回答 1

3

如果文件不存在,[NSFileHandle fileHandleForUpdatingAtPath:]则将返回nil(请参阅文档)。

因此,在尝试打开文件之前检查并在必要时创建它:

NSFileManager *fileMan = [NSFileManager defaultManager];
if (![fileMan fileExistsAtPath:appFile])
{
    [fileMan createFileAtPath:appFile contents:nil attributes:nil];
}
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
// etc.

并全面添加更多错误检查。

于 2013-02-22T13:42:46.737 回答