我想創建一個可變數組與一個名爲狗的自定義類的對象,並將其保存到iPhone文檔目錄中的文件,以便以後讀出該文件並返回到我的應用程序。我嘗試使用NSArray的writeToFile:atomically:方法來完成此操作,但是當我測試此方法的結果時,它始終返回NO值,並且未創建該文件,並且未存儲該數組。我對此有幾個問題。我應該將數組保存到什麼文件格式?以原子方式將數組寫入文件意味着什麼?一旦數組存儲在那裏,如何讀取文件的內容?最重要的是,爲什麼我的數組沒有存儲到指定路徑的文件中?謝謝你在前進,這裏是我使用我的應用程序的viewDidLoad方法中的代碼:保存NSMutableArray到iPhone文檔目錄
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
dogFilePath = [documentsDir stringByAppendingPathComponent:@"arrayDogsFile.plist"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSLog(@"%@",dogFilePath);
Dog *dog1 = [[Dog alloc] init];
dog1.name = @"Dog1";
Dog *dog2 = [[Dog alloc] init];
dog2.name = @"Dog2";
Dog *dog3 = [[Dog alloc] init];
dog3.name = @"Dog3";
NSMutableArray *arrayDogs = [NSMutableArray array];
[arrayDogs addObject: dog1];
[arrayDogs addObject: dog2];
[arrayDogs addObject: dog3];
//Sorts the array in alphabetical order according to name – compareDogNames: is defined in the Dog class
arrayDogs = (NSMutableArray *)[arrayDogs sortedArrayUsingSelector:@selector(compareDogNames:)];
if ([arrayDogs writeToFile:dogFilePath atomically:YES])
NSLog(@"Data writing successful");
else
NSLog(@"Data writing unsuccessful");
查找到歸檔/解檔 - 你的狗班將不得不採用NSCoding協議。 – 2012-04-22 16:09:37