开发者

What is the best way to store an array of objects with cocoa?

开发者 https://www.devze.com 2023-03-09 08:04 出处:网络
开发者_JS百科I have an NSMutableArray with many objects in it. Some are NSStrings, others are NSMutableArrays, others are NSNumbers. What is the best way to store this data so that the app could use i
开发者_JS百科

I have an NSMutableArray with many objects in it. Some are NSStrings, others are NSMutableArrays, others are NSNumbers. What is the best way to store this data so that the app could use it again?

The array needs to stay in order as well.

I'm thinking a plist or NSUserDefaults?

Many thanks


Consider using NSKeyedArchiver.

// Archive
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:theArray];
NSString *path = @"/Users/Anne/Desktop/archive.dat";
[data writeToFile:path options:NSDataWritingAtomic error:nil];

// Unarchive
NSString *path = @"/Users/Anne/Desktop/archive.dat";
NSMutableArray *theArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

It works great, especially in case the array contains more then strings and numbers.
This way you can be sure the unarchived array is identical to the original.


Assuming the other arrays also contain only numbers, strings, and arrays (or other property list types), a plist would be a great way to store your data. It will keep it's order, and is simple to use.

To write an array to a plist file, use writeToFile:atomically:.

[myArray writeToFile:@"path/to/file.plist" atomically:YES];

To read it, use initWithContentsOfFile:.

myArray = [[NSMutableArray alloc] initWithContentsOfFile:@"path/to/file.plist"];

However, that will create a mutable array with non-mutable contents. To create an array with mutable contents, you can use CFPropertyListCreateDeepCopy.

NSArray *temp = [[NSArray alloc] initWithContentsOfFile:@"path/to/file.plist"];
myArray = (NSMutableArray*) CFPropertyListCreateDeepCopy(kCFAllocatorDefault,(CFArrayRef)temp,kCFPropertyListMutableContainers);
[temp release];
0

精彩评论

暂无评论...
验证码 换一张
取 消