0

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

-(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属性保存到指定的属性列表路径。但这似乎不会发生一次。我重建应用程序。也许我创建新字典对象的方式不正确。有人可以解释为什么这不起作用吗?

4

2 回答 2

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];
}
于 2014-01-24T06:52:07.850 回答
0

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

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

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

并将文件保存到捆绑包中的路径。

如果您要修改捆绑包中的 plist 文件,您可以将文件保存在应用程序的文档中。

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

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

然后你把它和你的文件名结合起来,然后得到filePath.

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

最后你可以保存它:

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

于 2014-01-24T06:37:07.163 回答