I am facing a very weird problem with coredata.
I have an item managed with ids and i’m trying to update a dynamic property which is a simple NSNumber. I do this as always, in my item class:
- (int) hits{
return [self.hitNS intValue];
}
- (void) setHits:(int)h{
self.hitNS=[NSNumber numberWithInt:h];
}
Basically, i create my managed, object with this method:
[NSEntityDescription insertNewObjectForEntityForName:@"item"
inManagedObjectContext:[self getManagedObjetContextForCurrentThread]];
Then I update my hits, after I receive some data from the server.
CoreData tells me it updated the item, but when I access the item again:
-(NSArray *) getStoredEntities:(NSString*)entity withPredicate:(NSPredicate*)predicate
{
NSManagedObjectContext *moc=[self getManagedObjetContextForCurrentThread];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entity
inManagedObjectContext:moc]];
if (predicate)
[request setPredicate:predicate];
NSError *error = nil;
NSArray *fetchResults = [moc executeFetchRequest:request error:&error];
[request release];
return [fetchResults objectAtIndex:0];
}
Item *i=(Item*)[self getStoredEntity:@"Item"
withPredicate:[NSPredicate predicateWithFormat:@"(id==%@)", itemId]];
my property item.hits is not set to the new value, I get the old one.
What’s driving me nuts is that When I kill my app, and start again, my object is there and it works well. If y update my hits count, I get the good value…
So I think my problem is in some way connected to the first insertion of my object in CoreData…
Is there a cache I’m not seeing? Do I have to do something to “invalidate” my object?
Some help there would be really great!
That means your get/set managed contexts aren’t synced.
After you save a context the
NSManagedObjectContextDidSaveNotificationis sent and all other contexts interested in these changes have to observe this notification and then usemergeChangesFromContextDidSaveNotificationto synchronize.