保存NSMutableArray并将其加载到UITableView中

时间:2013-03-11 19:04:24

标签: xcode sdk nsmutablearray save tableview

我想保存多个NSMutableArray并加载它,因为这个数组从服务器获取内容,我不想在每次打开应用程序时重新加载该数据。 首先,我宣布了路径:

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从(...数组,即firstArray)加载数据,那么从服务器下载的数据未保存。

1 个答案:

答案 0 :(得分:0)

假设你使用的是MRC而不是ARC:
看起来你正在为自动释放的NSMutableArray设置一个ivar 尝试在retain上调用NSMutableArray,否则您的NSMutableArray将会被释放,因此在自动释放池耗尽时会被释放。 另一个解决方案是为每个NSMutableArray使用一个属性,如下所示:

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

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

您可以在https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

找到有关Objective-C内存管理的更多信息