將一個空的NSMutableArray寫入磁盤,然後再讀取它,它變成一個不可變的對象。
但是,如果NSMutableArray不是空的,它不會。如何解釋?
這裏是代碼:從plist讀取的空NSMutableArray變成不可變的對象
NSMutableArray *testItems1 = [NSMutableArray array];
NSMutableDictionary *testList1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:testItems1, @"list_items", @"list1", @"list_name", nil];
NSMutableArray *testItems2 = [NSMutableArray arrayWithObjects:@"item11", @"item22", nil];
NSMutableDictionary *testList2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:testItems2, @"list_items", @"list2", @"list_name", nil];
NSMutableArray *testLists = [NSMutableArray arrayWithObjects:testList1, testList2, nil];
[testLists writeToFile:@"/tmp/testLists" atomically:YES];
NSMutableArray *testReadLists = [NSMutableArray array];
[testReadLists setArray:[NSArray arrayWithContentsOfFile:@"/tmp/testLists"]];
NSMutableDictionary *testReadList = [testReadLists objectAtIndex:0];
NSMutableArray *testReadItems = [testReadList objectForKey:@"list_items"];
[testReadItems addObject:@"item3"]; // Crashes here: "*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'"
將數據寫入爲JSON。用NSJSONSerialization回讀,指定'NSJSONReadingMutableContainers'選項。 –
僅供參考 - 您的'/ tmp'路徑只會在模擬器中有效,或者可能是越獄的iOS設備。不要在「真實」代碼中使用這樣的路徑。 – rmaddy