1

I've just read some tutorials and decide to add Core Data storage to my project. Then I implement "create" and "read" methods. It works OK. But then I encountered a problem with "update" method.

- (void)updateForecastPlace:(NSString *)placeString
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    WFForecast *forecastToUpdate;

    for (WFForecast *forecast in fetchedObjects)
    {

        if ([[forecastToUpdate timestamp] compare:[forecast timestamp]] == NSOrderedAscending)
        {
            forecastToUpdate = forecast;
        }

    }

    [forecastToUpdate setPlace:placeString];
    error = nil;

    if ([context save:&error])
    {
        NSLog(@"Forecast information was updated!");
    }
    else
    {
        NSLog(@"The forecast information was not updated: %@", [error userInfo]);
    }

}

I'm fetching objects from context. (It's OK)

Then choose one to update.

Setup new value to its property( [forecastToUpdate setPlace:placeString];)

Then save the context. ( [context save:&error] )

It seems like it works (it's rise no errors and send success massage to console log). But when I read this object it appears to be non-updated. I read a lot of stuff on this problem but didn't figure out how to fix it. Any suggestions, please?

UPDATE: I check the value of my updated object property place

[forecastToUpdate setPlace:placeString];
NSLog(@"---arg value %@", placeString);
NSLog(@"---updated value %@", [forecastToUpdate place]);

and got the output like:

---arg value Sydney, Australia
---updated value (null)

Any idea what caused such mistake?

nadein
  • 357
  • 5
  • 14
  • 1
    your code seems ok, be sure you read the right object. also check if you have the right value of 'forecastToUpdate.place' just before saving the context – Idali Sep 15 '15 at 00:49
  • Idali, thanks. Your comment pushed me a little forward in my solution. (Check the update) – nadein Sep 15 '15 at 07:31

1 Answers1

0

Unfortunately the problem was in my inattentiveness :( I forgot to assign fetched object with my objectToUpdate pointer before compare values and do other stuff.

 WFForecast *lastestForecast = fetchedObjects[0]; // <- missed this row

for (WFForecast *forecast in fetchedObjects)
{
    NSLog(@"%@", [forecast place]);
    if ([[lastestForecast timestamp] compare:[forecast timestamp]] == NSOrderedAscending)
    {
        lastestForecast = forecast;
    }

}
nadein
  • 357
  • 5
  • 14