NSManagedObject
provides access to its NSManagedObjectContext
, but does it retain it?
According to "Passing Around a NSManagedObjectContext on iOS" by Marcus Zarra, "The NSManagedObject
retains a reference to its NSManagedObjectContext
internally and we can access it."
How does Zarra know this and is he correct?
I'm asking because I want to know if the NSManagedObjectContext
will be dealloc
'ed in the tearDown
method below. (I'm using CocoaPlant.)
#import <SenTestingKit/SenTestingKit.h>
#import <CocoaPlant/CocoaPlant.h>
#import "AccountUser.h"
@interface AccountUserTests : SenTestCase {
AccountUser *accountUser;
}
@end
@implementation AccountUserTests
- (void)setUp {
accountUser = [AccountUser insertIntoManagedObjectContext:
[NSManagedObjectContext contextWithStoreType:NSInMemoryStoreType error:NULL]];
}
- (void)tearDown {
[accountUser delete];
}
- (void)testFetchWithLinkedAccountUserID {
// Tests go here...
}
@end
NSManagedObject DOES NOT hold strong reference to its NSManagedObjectContext. I've checked that on a test project. Therefore, you should keep strong reference to NSManagedObjectContext as long as you use its objects.
Wow, over two years old and no accepted answer here :)
When I wrote that post I did indeed mean it keeps a reference to its associated NSManagedObjectContext
. If a NSManagedObject
retained the NSManagedObjectContext
then it would most likely run into problems.
In either case, whether the MOC is retained by the MO is irrelevant to your application design. If you need the MOC to stay around then you need to retain it (now referred to as a strong reference) or it will go away. What the frameworks do internally is not our problem. We just need to make sure we balance our retains and releases.
Matt,
I think Marcus may have miswrote that a NSManagedObject retains its context. Every NSManagedObject maintains a link to the context. Unless individual objects have an internal retain cycle or are retained outside of their context, then, in my experience, they are all released when the context is released. If they retained the context, then this would almost certainly not be the case.
The above said, you can easily write code to test Marcus' claim. Override -dealloc and log when it is called.
IMO, it is a best practice to retain your context until you are done with it. Depending on an undocumented behavior is probably not wise.
Andrew
来源:https://stackoverflow.com/questions/8378456/does-an-nsmanagedobject-retain-its-nsmanagedobjectcontext