问题
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.
回答1:
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.
回答2:
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.
回答3:
check the viewDidLoad-Method
profile = [NSEntityDescription insertNewObjectForEntityForName:@"MyProfile" inManagedObjectContext:profileContext];
hope this works
来源:https://stackoverflow.com/questions/7199143/core-data-attribute-changes-to-nil-arc-related