[英]NSDictionary doesn't save itself to a .plist file
我已经阅读了很多问答,但是他们并没有解决我的问题。
我编写了此方法,将笔尖中的一些数据保存到字典中,然后保存到.plist中
-(void)save{
NSString *saveFilePath = [self saveFilePath];
if ([[NSFileManager defaultManager]fileExistsAtPath:saveFilePath]) {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:saveFilePath];
//I Use the "today date" for key
NSDate *today = [[NSDate alloc]init];
NSMutableArray *array = [[NSMutableArray alloc]init];
NSString *delta = [[NSString alloc]initWithFormat:@"%d",[kmNew.text intValue] - [kmOld.text intValue]];
[array addObject:delta];
[array addObject:[consumoKg text]];
[array addObject:[consumoEuro text]];
[dictionary setObject:array forKey:today];
BOOL success = [dictionary writeToFile:[self saveFilePath] atomically:YES];
NSLog(@"%d",success);
[today release];
[delta release];
[array release];
[dictionary release];
}
else{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSDate *today = [[NSDate alloc]init];
NSMutableArray *array = [[NSMutableArray alloc]init];
NSString *delta = [[NSString alloc]initWithFormat:@"%d",[kmNew.text intValue] - [kmOld.text intValue]];
[array addObject:delta];
[array addObject:[consumoKg text]];
[array addObject:[consumoEuro text]];
[dictionary setObject:array forKey:today];
// Check if the value are store correctly into the dictionary
for (NSDate *key in dictionary) {
for (NSString *string in [dictionary objectForKey:key]) {
NSLog(@"%@",string);
}
}
BOOL success = [dictionary writeToFile:[self saveFilePath] atomically:YES];
NSLog(@"%d",success);
[today release];
[delta release];
[array release];
[dictionary release];
}
}
saveFilePath方法如下:
- (NSString *)saveFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilenameHistory];
}
变量已正确存储到字典中,但BOOL返回值“成功”为0。为什么?
我猜NSDictionary键必须是字符串。 保存到plist文件时,不允许使用NSDate。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.