【问题标题】:Saving a NSMutableArray into a txt-file / Loading txt-file back into NSMutableArray将 NSMutableArray 保存到 txt 文件/将 txt 文件加载回 NSMutableArray
【发布时间】:2011-03-22 12:20:46
【问题描述】:

我环顾四周,试图找到一种简单的方法,首先将 MutableArray(它将包含来自 UITextViews 的不同文本数组以及返回等)保存到 txt 文件中,然后将 txt 文件加载回我的 MutableArray .

我没有设法想出相反的方法(加载文本文件),我想知道我应该如何去做。我确定 txt 文件和可变数组并不真正兼容,特别是如果我希望 MutableArray 保存来自 UITextViews 的各种文本字符串。

有没有办法在可变数组中标记一个部分的开头,并在 txt 文件中标记下一个部分的开头?目的是能够在程序和简单的文本编辑器中编辑 txt 文件,而不会弄乱可变数组的结构。

我可以在我的文本文件中使用某个特殊字符(显然不是 \n)来分隔不同的对象吗?

这是我到目前为止的想法。抱歉,我是初学者,而且非常基础。第一个问题是我收到错误消息“NSMutableArray”可能无法响应“-writeToFile:atomically:encoding:error:”。接下来,我不知道如何将 txt 加载回我的数组中。最后,我想想出一种方法来分隔 txt 中的数组,使其保持可编辑状态,但这绝对是锦上添花。也许解决方案是将数组中的每个对象保存在单独的 txt 文件中,然后将每个 txt 加载到数组中?

// GENERATE ARRAY

NoteBook = [[NSMutableArray alloc] init];

for (int temp = 0; temp < 3; temp++) {
    [NoteBook insertObject:@"Title\n\n Line1\nLine2..." atIndex:temp];
}

// SAVING MY MUTABLE ARRAY

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

NSError *error;
BOOL succeed = [NoteBook writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myfile.txt"]
                          atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
    // Handle error here
}



// LOADING TEXTFILE AND PUT IT INTO A MUTABLE ARRAY
// NO IDEA... how to do this

【问题讨论】:

    标签: iphone objective-c cocoa-touch nsmutablearray


    【解决方案1】:

    将您的数组转换为字符串,反之亦然,例如,使用

    NSString* arrayText = [NoteBook componentsJoinedByString: @"<your-favourite-separator-string>"];
    

    使用 [arrayText writeToFile...] 写入文件

    从文件中读回字符串后,使用

    Notebook = [arrayText componentsSeparatedByString: @"<your-favourite-separator-string>"];
    

    最后,不要这样做。将您的数组直接保存到属性列表(阅读这些)或 JSON 或其他一些结构化数据格式。

    【讨论】:

    • 谢谢。我没有尝试过,但理论上它是完全合理的。为什么你建议我不应该这样做呢?如果我的目标是尽可能轻松地编辑 txt,我为什么不这样做并选择 JSON 呢?此外,您不能使用文本编辑器非常轻松地(如果有的话)编辑 plist。
    • 不,你是对的。如果考虑到可读性,纯文本当然会胜出。
    • 嗨,我刚试过这个,第一步完美。但是,当尝试将信息读回我的程序时,尝试将数组转换为 MutableArray NoteBook 时似乎存在冲突:NoteBook = [tempTextOut componentsSeparatedByString: @"\n--- end of page ---\n"]; xCode 告诉我:分配“struct NSArray*”的不兼容的 Objective-C 类型,预期'结构 NSMutableArray*'`。我想这个错误信息很清楚,但我怕我不明白这里的问题。如果您能解释错误消息,我将不胜感激。谢谢!!
    • 刚刚在其他人的帮助下解决了这个问题:stackoverflow.com/questions/5405328/…
    【解决方案2】:

    为什么不直接将可变数组转换为 JSON 并将该字符串写入文件?逆向是从文件中读取字符串并使用 JSON 解析器转回数组。 json-framework 非常好用。

    一个好处是,只要您编写有效的 JSON,您就可以通过编辑文本文件来创建或修改数组。

    【讨论】:

    • 感谢您的建议,我将仔细研究 JSON。但我想我宁愿坚持使用没有任何格式的纯 txt 文件。我想唯一的解决方案是为数组中的每个对象创建一个单独的文件。
    • 你会喜欢 JSON 一旦你尝试它。例如,它的可读性很强,标点符号比 XML 少。这是一个很好的 JSON 验证器,用于检查您自己编写的任何内容或很好地对其进行格式化:jsonlint.com
    【解决方案3】:
    1. 将 NSMutableArray 设为 NSArray 。因为 NSMutableArray 没有 writeToFile 。
    2. 从文件中检索数组

      NSArray *theCatalogInfo=nil;
      NSString *theCatalogFilePath = [NSString stringWithFormat:@"%@/Documents/",NSHomeDirectory()];
      theCatalogFilePath = [theCatalogFilePath stringByAppendingString:kCatalogCachePath];
      if(nil!=theCatalogFilePath)
      {
          theCatalogInfo=[[NSArray alloc]initWithContentsOfFile:theCatalogFilePath];
      }
      
    3. 将数组保存到文件

      NSString *theCatalogFilePath = [NSString stringWithFormat:@"%@/Documents/",NSHomeDirectory()];
      theCatalogFilePath = [theCatalogFilePath stringByAppendingString:kCatalogCachePath];
      
      [**YourArray** writeToFile:theCatalogFilePath atomically:YES];
      

    【讨论】:

    • NSMutableArray 是 NSArray 的子类,因此 NSMutableArray 响应 writeToFile:atomically:。无需创建 NSArray。
    【解决方案4】:

    看看以下三种方法来创建一个文本文件,写入它并从中读取数据。 关键是存储不同的对象,用空格隔开。而且你应该很简单。

    -(void)createFile
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Sample.txt"]; 
    
        NSFileManager * file_manager = [NSFileManager defaultManager];
    
        if(![file_manager fileExistsAtPath:filePath])
        {
            [file_manager createFileAtPath:filePath contents:nil attributes:nil];
    
            NSString *content = @"NULL NULL NULL";
            [content writeToFile:filePath 
                      atomically:NO 
                        encoding:NSStringEncodingConversionAllowLossy 
                           error:nil];
        }
    
    }
    
    -(void)writeToFile
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Sample.txt"]; 
    
        NSString *content = [NSString stringWithFormat:@"%@ %@ %@", obj1, obj2, obj3];
    
        [content writeToFile:filePath 
                    atomically:NO 
                    encoding:NSStringEncodingConversionAllowLossy 
                    error:nil];
    }
    
    -(void)readFromFile
    {
        objects = [[NSArray alloc] init];
        NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Sample.txt"]; 
        if (filePath) {  
            NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:nil];  
            if (myText) { 
                objects = [myText componentsSeparatedByString:@" "];
            }
        }
    
    }
    

    【讨论】:

    • NSStringEncodingConversionAllowLossy 不是有效的编码。如果覆盖writeToFile 中的文件,createFile 是无用的方法。如果您在下一行创建另一个文件,createFileAtPath:contents:attributes: 是多余的。你在readFromFile 的第一行和最后一行泄漏了旧对象。现在没有人使用 ascii。
    • @fluchtpunkt:哎呀......在我非常缺乏经验的眼里,它看起来像是一个相当结构化的回复。
    【解决方案5】:

    如果您的 nsarray 包含 nsdictionary、nsarray、nsstring、nsnumber、nsdata 或 nsdate 对象(没有自定义对象、int 等),您可以简单地将可变数组的内容写入 plist 文件。

    这将维护您拥有的数据结构,您可以直接将该数据读入数组。我如何在我的几个数据类中做到这一点是

    NSArray *tempArray = [NSArray arrayWithContentsOfFile:[Utils getFileLocation]];
    if (tempArray == nil) {
        yourArray = [[NSMutableArray alloc] init];
    } else {
        yourArray = [[NSArray deepMutableCopy:tempArray] retain];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多