【问题标题】:Overwriting the previous file in NSDocumentDirectory覆盖 NSDocumentDirectory 中的前一个文件
【发布时间】:2013-03-31 15:39:00
【问题描述】:

我已使用此代码将字符串写入同一个文件 10 次。但它会覆盖每次新发布的先前数据。我想将新数据附加到旧数据中。

[@"one" writeToFile:[self returnDocumentsDirectory] atomically:NO encoding:NSASCIIStringEncoding error:nil];


-(NSString *)returnDocumentsDirectory
{
    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"];
    return filePath;
}

【问题讨论】:

    标签: objective-c xcode nsfilemanager


    【解决方案1】:

    使用以下代码写入文件

    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"];
    
    // Create a FileHandle
    NSFileHandle *myHandle;
    

    将以下代码放入循环中以进行多次追加操作

    // Check File Exist at Location or not, if not then create new
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
       [[NSFileManager defaultManager] createFileAtPath:filePath contents:[@"Your First String" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
    
    // Create handle for file to update content
    myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    
    // move to the end of the file to add data
    [myHandle seekToEndOfFile];
    
    // Write data to file
    [myHandle writeData:  [@"YOUr Second String" dataUsingEncoding:NSUTF8StringEncoding]];
    
    // Close file
    [myHandle closeFile];
    

    【讨论】:

      猜你喜欢
      • 2012-08-13
      • 2014-02-05
      • 2018-05-22
      • 2019-12-27
      • 1970-01-01
      • 2011-11-19
      • 2017-08-31
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多