保存NSArray
问题描述:
我想将NSArray保存为文件或可能使用用户默认值。
I would like to save an NSArray either as a file or possibly use user defaults. Here's what I am hoping to do.
- 检索已保存的NSArray(如果有)。
这是可能的,如果是这样,我该怎么办?
Is this possible, and if so how should I do this?
答
NSArray提供了两种方法来完成你想要的: initWithContentsOfFile:
和 writeToFile:atomically:
NSArray provides you with two methods to do exactly what you want: initWithContentsOfFile:
and writeToFile:atomically:
一个简短的示例可能如下所示:
A short example might look like this:
//Creating a file path under iOS:
//1) Search for the app's documents directory (copy+paste from Documentation)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];
//Load the array
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
if(yourArray == nil)
{
//Array file didn't exist... create a new one
yourArray = [[NSMutableArray alloc] initWithCapacity:10];
//Fill with default values
}
...
//Use the content
...
//Save the array
[yourArray writeToFile:yourArrayFileName atomically:YES];