将NSMutableArray写入文件并加载回来

use*_*517 4 file-io cocoa cocoa-touch objective-c nsmutablearray

我正在做一些关于写入和加载文件的练习.

我创建了一个NSString,然后将其写入文件,然后NSString再次加载.简单.

我怎样才能做到这一点用NSMutableArray的NSStrings,或者更好的NSMutableArray是我自己的类?

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // insert code here...

        //write a NSString to a file
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

        NSString *str = @"hello world";
        NSArray *myarray = [[NSArray alloc]initWithObjects:@"ola",@"alo",@"hello",@"hola", nil];

        [str writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];

        //load NSString from a file
        NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
        NSString *filePath2 = [documentsDirectory2 stringByAppendingPathComponent:@"file.txt"];
        NSString *str2 = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];

        NSLog(@"str2: %@",str2);

    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

印刷:str2:你好世界

Rob*_*Rob 10

如果你想把你的数组写成plist,你可以

// save it

NSArray *myarray = @[@"ola",@"alo",@"hello",@"hola"];
BOOL success = [myarray writeToFile:path atomically:YES];
NSAssert(success, @"writeToFile failed");

// load it

NSArray *array2 = [NSArray arrayWithContentsOfFile:path];
NSAssert(array2, @"arrayWithContentsOfFile failed");
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅" 属性列表编程指南"中的使用Objective-C方法读取和写入属性列表数据.

但是,如果您想保留对象的可变性/不变性(即精确的对象类型),并且打开保存更多对象类型的可能性,您可能希望使用存档而不是plist:

NSMutableString *str = [NSMutableString stringWithString:@"hello world"];
NSMutableArray *myarray = [[NSMutableArray alloc] initWithObjects:str, @"alo", @"hello", @"hola", nil];

//save it

BOOL success = [NSKeyedArchiver archiveRootObject:myarray toFile:path];
NSAssert(success, @"archiveRootObject failed");

//load NSString from a file

NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSAssert(array2, @"unarchiveObjectWithFile failed");
Run Code Online (Sandbox Code Playgroud)

虽然我用数组说明了这个技术,但它适用于任何符合的对象 NSCoding(包括许多基本的Cocoa类,如字符串,数组,字典NSNumber等).如果你想让你自己的课程合作NSKeyedArchiver,那么你也必须使它们符合要求NSCoding.有关更多信息,请参阅" 存档和序列化编程指南".