簡體   English   中英

保存NSArray

[英]Saving a NSArray

我想將NSArray保存為文件或可能使用用戶默認值。 這是我希望做的。

  1. 檢索已保存的NSArray(如果有)。
  2. 用它做點什么。
  3. 刪除已保存的數據(如果有)。
  4. 保存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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM