xcode 用可可存储对象数组的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6192778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to store an array of objects with cocoa?
提问by laxj11
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?
我有一个 NSMutableArray,里面有很多对象。有些是 NSStrings,有些是 NSMutableArrays,有些是 NSNumbers。存储此数据以便应用程序可以再次使用它的最佳方法是什么?
The array needs to stay in order as well.
阵列也需要保持有序。
I'm thinking a plist or NSUserDefaults?
我在想 plist 还是 NSUserDefaults?
Many thanks
非常感谢
采纳答案by Anne
Consider using NSKeyedArchiver
.
考虑使用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.
它工作得很好,特别是在数组包含更多字符串和数字的情况下。
这样您就可以确保未归档的数组与原始数组相同。
回答by ughoavgfhw
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.
假设其他数组也只包含数字、字符串和数组(或其他属性列表类型),plist 将是存储数据的好方法。它将保持秩序,并且易于使用。
To write an array to a plist file, use writeToFile:atomically:
.
要将数组写入 plist 文件,请使用writeToFile:atomically:
.
[myArray writeToFile:@"path/to/file.plist" atomically:YES];
To read it, use initWithContentsOfFile:
.
要阅读它,请使用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
.
但是,这将创建一个具有非可变内容的可变数组。要创建具有可变内容的数组,您可以使用CFPropertyListCreateDeepCopy
.
NSArray *temp = [[NSArray alloc] initWithContentsOfFile:@"path/to/file.plist"];
myArray = (NSMutableArray*) CFPropertyListCreateDeepCopy(kCFAllocatorDefault,(CFArrayRef)temp,kCFPropertyListMutableContainers);
[temp release];