清除文件内容

Joh*_*rad 4 file-io objective-c ios

我正在尝试删除iOS的内容文本文件。

另外,我可以删除文件,然后在没有内容的情况下立即重新创建它。

对于此解决方案,我知道我可以使用删除文件[fileManager removeItemAtPath:filePath error:&error];。重新创建文件对我来说是困难的部分。

我使用以下代码定位文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile.txt"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if([fileManager fileExistsAtPath:filePath])
{
    [fileManager removeItemAtPath:filePath error:&error];
}

//code to recreate the same file, just with no content
Run Code Online (Sandbox Code Playgroud)

Mar*_*0ux 5

尝试

-[[NSFileManager defaultManager] createFileAtPath:path contents:[NSData data] attributes:nil]
Run Code Online (Sandbox Code Playgroud)