0

是否可以防止删除未设置的属性(在 plist 中)?

我的代码:

- (NSString*)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}

- (void)store {
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setValue:textField.text forKey:@"text"];
        [dict setValue:textField2.text forKey:@"text2"];
        [dict writeToFile:[[self dataFilePath] stringByAppendingPathComponent:fileName] atomically:NO];
    }
}

- (void)load {
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[[self dataFilePath] stringByAppendingPathComponent:fileName]];
        textField.text = [dict objectForKey:@"text"];
        textField2.text = [dict objectForKey:@"text2"];
    }
}

如果我注释掉该行[dict setValue:textField2.text forKey:@"text2"];,该属性将被删除。是否可以说覆盖属性,但保持存在?

迈克

4

2 回答 2

0

你可以附加你的字符串,然后像这样存储在 plist 中:

 - (void)store {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    NSString *strText = [dict objectForKey:@"text"];
    [dict setValue:[strText stringByAppendingString:textField.text] forKey:@"text"];
     NSString *strText2 = [dict objectForKey:@"text2"];
    [dict setValue:[strText2 stringByAppendingString:textField2.text] forKey:@"text2"];
    [dict writeToFile:[[self dataFilePath] stringByAppendingPathComponent:fileName] atomically:YES];
  }
}
于 2012-09-11T11:57:57.803 回答
0

这是我的解决方案:

- (NSString*)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

- (void)storeDictionary:(NSDictionary*)values {
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
        NSMutableDictionary *dict = [self load];
        NSArray *allKeys = values.allKeys;
        for (int i = 0; i < allKeys.count; i++) {
            [dict setValue:[values objectForKey:[allKeys objectAtIndex:i]] forKey:[allKeys objectAtIndex:i]];
        }
        [dict writeToFile:[[self dataFilePath] stringByAppendingPathComponent:fileName] atomically:NO];
    }
}

- (NSMutableDictionary*)load {
    NSMutableDictionary *dict;
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
        dict = [[NSMutableDictionary alloc] initWithContentsOfFile:[[self dataFilePath] stringByAppendingPathComponent:fileName]];
    }
    return dict;
}

迈克

于 2012-09-11T12:35:14.290 回答