2013-03-11 78 views
0

我想保存多個NSMutableArray並加載它,因爲此數組從服務器獲取內容,並且我不想在每次打開該應用程序時重新加載該數據。 首先我聲明的路徑:保存NSMutableArray並將其加載到UITableView中

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *firstPath = [documentsDirectory stringByAppendingPathComponent:@"first"]; 
    NSString *secondPath = [documentsDirectory stringByAppendingPathComponent:@"second"]; 
    NSString *thirdPath = [documentsDirectory stringByAppendingPathComponent:@"third"]; 
    NSString *fourthPath = [documentsDirectory stringByAppendingPathComponent:@"fourth"]; 

然後保存NSMutableArrays:

  [firstArray writeToFile:firstPath atomically:YES]; 
     [secondArray writeToFile:secondPath atomically:YES]; 
     [thirdArray writeToFile:thirdPath atomically:YES]; 
     [fourthArray writeToFile: fourthPath atomically:YES]; 

然後在其他NSMutableArrays打開這些文件:

firstArrayget = [NSMutableArray arrayWithContentsOfFile:firstPath]; 
    secondArrayget = [NSMutableArray arrayWithContentsOfFile:secondPath]; 
    thirdArrayget = [NSMutableArray arrayWithContentsOfFile:thirdPath]; 
    fourthArrayget = [NSMutableArray arrayWithContentsOfFile:fourthPath]; 

然後我嘗試加載這些陣列(。 ..Arrayget即firstArrayget)成一個TableView。

得到的數據加載到的TableView,但是當我向下滾動應用程序與錯誤崩潰:

*** -[CFArray objectAtIndex:]: message sent to deallocated instance 0x930fc80 

,並在文件中:

Thread 1:EXC_BREAKPOINT(code=EXC_1386_BPT,subcode=0x0) 

但如果我說的TableView到從(... Array即firstArray)加載數據,所以從服務器下載的數據未保存。

回答

0

假設你使用的是MRC而不是ARC:
看起來你正在爲自動發佈的NSMutableArray設置一個ivar。
試着在NSMutableArray上調用retain,否則你的NSMutableArray就會被釋放,並在autoreleasepool消失時釋放。 另一種解決方案是使用一個屬性爲每個NSMutableArray S的是這樣的:

// Create a property in your header file 
@property (retain) NSMutableArray *firstArrayget; 

// And set the property in your method 
[self setFirstArrayGet:[NSMutableArray arrayWithContentsOfFile:firstPath]]; 

你可以找到更多有關Objective-C的內存管理在https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

+0

非常感謝您!這幫助了我。 – hannsch 2013-03-11 19:21:43

相關問題