我希望将NSArray保存为文件,或者使用用户默认设置。我希望这样做。
这有可能吗?如果是的话,我该怎么做呢?
发布于 2009-09-28 15:19:29
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];发布于 2009-09-28 16:54:50
可以在数组包含的对象上实现NSCoding,并使用NSKeyedArchiver将数组序列化/反序列化为磁盘。
BOOL result = [NSKeyedArchiver archiveRootObject:myArray toFile:path];归档程序将遵从您的NSCoding实现,从每个对象获取可序列化的值,并编写一个可以用NSKeyedUnarchiver读取的文件。
id myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];更多信息在系列化指南。
发布于 2009-09-28 15:17:22
这似乎是最适合核心数据的问题,因为这将处理所有持久的对象数据。当您检索数据时,它将返回一个未排序的NSSet,因此您必须有某种方式对数组中的数据进行排序,例如与您创建的每个对象合并一个唯一的id号。
https://stackoverflow.com/questions/1487606
复制相似问题