NSDictionary不会将自身保存为.plist文件

时间:2011-10-12 10:02:25

标签: objective-c plist nsdictionary

我读了很多q& 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 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值“success”为0 ..为什么?

1 个答案:

答案 0 :(得分:1)

我猜NSDictionary键必须是字符串。保存到plist文件时不允许使用NSDate。