如果文件存在NSFileManager,请不要保存到文件

时间:2013-01-30 07:45:37

标签: ios nsfilemanager

我有一个搜索文件的NSFileManager,如果该文件不存在则会创建一个文件,如果它确实存在,则会写入该文件。但我想要的是,如果文件存在,它不会写入它。这是我的代码。

NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSLog(@"%@", docPath);
NSString *results=[docPath stringByAppendingPathComponent:@"results.csv"];

if (![[NSFileManager defaultManager] fileExistsAtPath:results]) {
    [[NSFileManager defaultManager]
     createFileAtPath:results contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:results];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[save dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
NSLog(@"info saved");

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您应该接受Flexicoder的回答,但很明显,如果saveNSString,您可以稍微简化一下:

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *results = [docPath stringByAppendingPathComponent:@"results.csv"];

if (![[NSFileManager defaultManager] fileExistsAtPath:results])
    [save writeToFile:results atomically:YES encoding:NSUTF8StringEncoding error:nil];

答案 1 :(得分:1)

将所有代码包含在if语句

NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSLog(@"%@", docPath);
NSString *results=[docPath stringByAppendingPathComponent:@"results.csv"];

if (![[NSFileManager defaultManager] fileExistsAtPath:results]) {
    [[NSFileManager defaultManager]
 createFileAtPath:results contents:nil attributes:nil];
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:results];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[save dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandle closeFile];
    NSLog(@"info saved");
}