读取和写入NSMutableArray到iPhone不工作(在iOS模拟器上工作)

时间:2015-03-31 22:24:58

标签: ios objective-c iphone file

在我正在处理的应用程序中,我希望有一个NSMutableArray(称为pathsArray),我可以从应用程序目录中的文件中读取,能够创建该数组的实例,我可以添加对象和/或删除来自的对象,然后我想把它写回文件。我有一个UILabel,显示此数组中的内容数。我的问题:我的代码在Xcode的iOS模拟器上工作正常但是当我尝试在我的实际iPhone上运行应用程序时,数据不会被保存。我知道这里有很多关于这个问题的问题,但我似乎无法看到我做错了什么。任何帮助将不胜感激。

- (void) loadArrayContents {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingString:@"theArray"];

//Objects contained in an array returned by 'initWithContentsOfFile' are immutable even if the array is mutable
NSArray* contentsArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
pathsArray = [[NSMutableArray alloc] initWithArray:contentsArray];
}

和...

- (void) saveArrayContents {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingString:@"theArray"];

[pathsArray writeToFile:filePath atomically:YES]);
}

1 个答案:

答案 0 :(得分:2)

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"theArray"];

应该解决问题。

的问题
NSString *filePath = [documentsDirectory stringByAppendingString:@"theArray"];

是它不会在文件路径中添加/