【问题标题】:Saving an Mutable Array into file via writeToFile通过 writeToFile 将可变数组保存到文件中
【发布时间】:2013-05-03 05:42:11
【问题描述】:
for(int x = 0; x < [tags count]; x++){
    NSString* tagsValue = [[NSString alloc] initWithFormat:@"%d: %f", 1, 
    [[tags objectAtIndex:x]doubleValue]];

    [[tagsValue dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath 
    atomically:NO];
}

我知道 writeToFile 将替换文件本身,因此它会给出数组值的最终值。 我怎么能解决这个问题我一直试图解决这个问题几个小时但我没有运气谢谢! :)

【问题讨论】:

  • 你想做什么?你正在尝试写一个字符串

标签: ios for-loop nsmutablearray writetofile


【解决方案1】:

我认为您正在尝试将数组直接写入文件。

  1. 将数组转换为字符串格式。

    NSString *tagsCompleteStr = [tags componentJoinedByString:@" "];
    [tagsCompleteStr  writeToFile:fileAtPath 
                                           atomically:NO];
    

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    以下代码将在文件末尾添加 tagsValue 字符串,
    确保您已经创建了文件。

       for(int x = 0; x < [tags count]; x++){
           NSString* tagsValue = [[NSString alloc] initWithFormat:@"%d: %f", 1, [[tags objectAtIndex:x]doubleValue]];
           NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:fileAtPath];
           [myHandle seekToEndOfFile];
           [myHandle writeData:[tagsValue dataUsingEncoding:NSUTF8StringEncoding]];
       }
    

    【讨论】:

    • 非常感谢!这实际上有效:D 但我如何能够使用该文件来提取信息我可以重新制作一个数组????
    • 试试这个,NSArray *lines = [[NSString stringWithContentsOfFile:fileAtPath encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByString:@"\n"];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    相关资源
    最近更新 更多