[英]Saving a NSArray
我想將NSArray保存為文件或可能使用用戶默認值。 這是我希望做的。
這是可能的,如果是這樣,我該怎么做?
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];
您可以對陣列包含的對象實施NSCoding ,並使用NSKeyedArchiver將陣列序列化/反序列化為磁盤。
BOOL result = [NSKeyedArchiver archiveRootObject:myArray toFile:path];
歸檔程序將遵循您的NSCoding實現,以從每個對象獲取可序列化的值,並編寫可以使用NSKeyedUnarchiver讀取的文件:
id myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
序列化指南中的更多信息。
這似乎是最適合Core Data的問題,因為這將處理所有持久對象數據。 當您檢索數據時,它將返回一個未分類的NSSet,因此您必須有一些方法對數組中的數據進行排序,例如與您創建的每個對象關聯的唯一ID號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.