如何将新的NSMutableDictionary保存到属性列表中

时间:2014-01-24 06:24:28

标签: ios iphone objective-c dictionary property-list

我在这里有这个方法,每次按下保存时都会运行:

-(void)setName:(NSString *)foodName andCarbs:(NSNumber *)carbAmount{
    [self.userFoodDictionary setObject:(NSString *)foodName forKey:(NSString *)foodName];
    NSString *value = [[NSString alloc] initWithFormat:@"%@ Value", foodName];
    [self.userFoodDictionary setObject:(NSNumber *)carbAmount forKey:(NSString *)value];
    [self.userFoodDictionary writeToFile:self.appDataPath atomically:YES];
}

根据我的理解,第二行应该将userFoodDictionary属性保存到指定的属性列表路径。但这似乎不会发生过一次。我重建了应用程序。也许我创建新词典对象的方式不正确。有人可以解释为什么这不起作用吗?

2 个答案:

答案 0 :(得分:1)

写入Plist

- (NSString *)foodDataPlistFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"UserFoodData.plist"];

    return filePath;
}

...

-(void)setName:(NSString *)foodName andCarbs:(NSNumber *)carbAmount{
    [self.userFoodDictionary setObject:(NSString *)foodName forKey:(NSString *)foodName];
    NSString *value = [[NSString alloc] initWithFormat:@"%@ Value", foodName];
    [self.userFoodDictionary setObject:(NSNumber *)carbAmount forKey:(NSString *)value];
    NSString *filePath = [self foodDataPlistFilePath];
    [self.userFoodDictionary writeToFile:filePath atomically:YES];
}

初始化可变字典:

NSString *filePath = [self foodDataPlistFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
self.userFoodDictionary = [[NSMutableDictionary alloc] init];
if(fileExists){
    NSDictionary *foodData = [NSDictionary dictionaryWithContentsOfFile:filePath];
    [_userFoodDictionary setDictionary:foodData];
}

答案 1 :(得分:0)

您无法修改捆绑包中的文件。

正如您在评论中所说,您初始化self.appDataPath:

NSString *appDataPath = [[NSBundle mainBundle] pathForResource:@"UserFoodData" ofType:@"plist"];

并将文件保存到bundle中的路径。

如果要修改bundle中的plist文件,可以将该文件保存在app的文档中。

您可以通过以下方式获取文档路径:

NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

然后将它与您的文件名组合,然后获取filePath

NSString * filePath = [documentPath stringByAppendingPathComponent:@"UserFoodData.plist"];

最后你可以保存它:

[self.userFoodDictionary writeToFile:filePath atomically:YES];