Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data attribute changes to nil (ARC related?)

I have some Core Data functionality that was working fine until some recent (seemingly unrelated) changes were made. Now I'm getting problems where all the attributes belonging to a particular NSManagedObject subclass instance are suddenly returning nil.

Let's say my NSManagedObject subclass is called Foo and it has only one attribute called value. Once I realised value was somehow becoming nil I went and setup the following category to monitor changes to value.

@implementation Foo (Debug)

- (void)setValue:(NSDate *)value
{
    [self willChangeValueForKey:@"value"];
    [self setPrimitiveValue:value forKey:@"value"];     
    [self didChangeValueForKey:@"value"];
}

- (NSDate *)value
{
    [self willAccessValueForKey:@"value"];
    NSDate *value = [self primitiveValueForKey:@"value"];
    [self didAccessValueForKey:@"value"];

    return value;
}

@end

setValue: is called for my object and the argument passed in is a non-nil NSDate. Then the value is retrieved (in another method). The same value that was specified is retrieved correctly.

However when another method tries to read value, the value accessor is called and a nil value is returned by primitiveValueForKey:.

In between the two reads setValue: is not called and the Foo object itself is still valid (non-nil). In fact no other Core Data operations are performed between the two reads on any Core Data object or the context as a whole.

We're using ARC in our project. Is it possible ARC is somehow messing with my Core Data variables and deallocating them? If so does anybody have any suggestions for debugging ARC deallocations? Or better yet, does anyone know a way to ensure ARC doesn't deallocate my variable.

This may not even be ARC related, however I'm at a bit of a loss as to what is going on. Any suggestions would be very much appreciated.

like image 708
Benjamin Dobell Avatar asked Aug 26 '11 01:08

Benjamin Dobell


2 Answers

This is very likely because the NSManagedObjectContext that these objects belong to, is going away. When you have NSManagedObject instances around but you're not holding on to the context yourself, those managed objects will start returning nil.

Under ARC, make sure you store the context in a strong variable, i.e. an instance variable that's not weak or a static global.

Non-ARC, i.e. retain-release code, make sure you're retaining the context.

like image 199
Daniel Eggert Avatar answered Oct 23 '22 23:10

Daniel Eggert


As others mentioned (it was my case also), be sure that you haven't reset your managed object context because if you do, all Entities stored as properties will have data: <fault>.

If you do reset your managed object context, you will also have to re-fetch the Entity itself.

like image 31
Kansway Avatar answered Oct 24 '22 00:10

Kansway