Write an NSMutableArray to a file and load it back

风流意气都作罢 提交于 2019-12-01 19:44:22

If you want to write your array as a plist, you can

// 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");

For more information, see Using Objective-C Methods to Read and Write Property-List Data in the Property List Programming Guide.

But, f you want to preserve the mutability/immutability (i.e. the precise object types) of your objects, as well as open up the possibility of saving a wider array of object types, you might want to use an archive rather than a 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");

While I illustrate the technique with an array, it works with any object that conforms to NSCoding (which includes many of the basic Cocoa classes like strings, arrays, dictionaries, NSNumber, etc.). If you want to make your own classes work with NSKeyedArchiver, then you must make them conform to NSCoding, too. For more information, see the Archives and Serializations Programming Guide.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!