我已经按照了一些教程,搜索了问题并且无法理解为什么我无法将数据保存到属性列表
在我的研究中我能够确定'writeToFile'返回0,这可能是由于自定义数据类型(类),但我试图保存的是一个与属性列表兼容的NSNumber。
请帮助,因为我无法解决为什么这不会保存,我在iPhone模拟器中测试,没有在〜/ Documents文件夹中创建文件
此致
- (void)saveData{
NSLog(@"*** SAVING DATA ***");
DataManager *datamgr = [DataManager sharedManager];
NSString *error;
//get path of data plist in users Document directory
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];
NSNumber *gems = [NSNumber numberWithInt:datamgr.gemCount];
//create arrays for data and keys
NSArray *data = [NSArray arrayWithObjects:gems, nil];
NSArray *keys = [NSArray arrayWithObjects:@"Gems", nil];
//create dictionary with data against keys
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects:data forKeys:keys];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
//write file from dictionary
if(plistData) {
if([plistData writeToFile:plistPath atomically:YES] != 0){
NSLog(@"write file to plist");
}
}
else {
NSLog(@"%@",error);
}
}
答案 0 :(得分:3)
我唯一看错的是您正在搜索的目录。尝试更改:
//get path of data plist in users Document directory
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0];
对此:
//get path of data plist in users Document directory
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
我还建议在物理设备上进行调试,模拟器没问题,但在某些情况下它确实有自己的问题。