Jos*_*hua 21 cocoa objective-c
我想将NSArray保存为文件或可能使用用户默认值.这是我希望做的.
这是可能的,如果是这样,我该怎么做?
rlu*_*uba 39
NSArray为您提供了两种方法来完成您想要的任务:initWithContentsOfFile:和writeToFile:atomically:
一个简短的例子可能如下所示:
//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];
Run Code Online (Sandbox Code Playgroud)
dst*_*rkr 14
您可以对阵列包含的对象实施NSCoding,并使用NSKeyedArchiver将阵列序列化/反序列化为磁盘.
BOOL result = [NSKeyedArchiver archiveRootObject:myArray toFile:path];
Run Code Online (Sandbox Code Playgroud)
归档程序将遵循您的NSCoding实现,以从每个对象获取可序列化的值,并编写可以使用NSKeyedUnarchiver读取的文件:
id myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
Run Code Online (Sandbox Code Playgroud)
序列化指南中的更多信息.
| 归档时间: |
|
| 查看次数: |
21558 次 |
| 最近记录: |