NSDictionary doesn't save itself to a .plist file
I've read a lot of q&a but they didn't solve my problem.
I wrote this method to save some data from my nib to a dictionary and then to a .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 a开发者_如何转开发lloc]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];
}
}
The saveFilePath method is the following:
- (NSString *)saveFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilenameHistory];
}
The variables are stored correctly into the dictionary, but the return BOOL value "success" is 0.. Why?
I guess NSDictionary keys must be strings. NSDate is not allowed when saving to plist file.
精彩评论