Pregunta

i've got this method here which runs through every time I press save:

-(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];
}

From my understanding, the second last line should save the userFoodDictionary properties to the specified property list path. But that doesn't seem to happen once. I rebuild the application. Maybe my way of creating a new dictionary object is incorrect. Could someone please explain why this isn't working?

¿Fue útil?

Solución

Write to 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];
}

Initialize mutable dictionary:

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];
}

Otros consejos

You can't modify the file in bundle.

As you said in comment, you init self.appDataPath:

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

and save the file to the path which is in bundle.

If you would modify the plist file in bundle, you could save the file in app's document.

You can get the document path through:

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

then you combine it with your filename, then get the filePath.

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

At last you can save it:

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top