views:

39

answers:

2

Hello

I was analyzing my app with leaks, and i observe that some core data entity is leaking, how can a NSManagedObject leak? I thought it was managed by the operating system? Are there known leaks in core data? The line that Leaks says causes the leak is

NSMutableArray *e=[NSMutableArray  arrayWithArray:[[user videos] allObjects]];
    //the line above ^ is pointed to by leaks as generating a leak
for(VideoEntity * v in e)
{
    UploadThread *ut= [[UploadThread alloc] init];
    [ut setVideoEntity:v];
    [threads addObject:ut];
    [ut release];
}

Where user is a managed object which contains VideoEntity as a to-many relationship, and I assign the VideoEntitys to some threads to operate on...Leaks says VideoEntity is leaking.

Does anyone have any input?

Thanks

Daniel

+1  A: 

UploadThread may be retaining it and never releasing it. Yes, NSManagedObjects can leak. They're just objects. They are part of the same memory management that the rest of the system uses.

Kevin Ballard
Thats an intersting points, I though one was not suppose to retain or release managed objects, but the setter for UploadThread is declared as retain, which should probably not be! Does calling retain actually have a leak (memory not being reallocated) even though the object is still managed by the system?
Daniel
Nope, you're definitely supposed to retain/release them. They're normal obj-c objects, they just have some extra management done by the context. If you don't retain/release the objects, then they may stay around or they may disappear out from under you, depending on whether the context decides to hold onto them or not. You should ignore the context when thinking about memory management on them and just treat them like any other model object.
Kevin Ballard
+1  A: 

Managed Objects that have relationships have implicit retain cycles (i.e., both sides of the relationship retain their objects). Once you fault in a relationship, you create this retain cycle. To break it, you need to call -[ManagedObjectContext refreshObject:mergeChanges:] to re-fault the object and break the retain cycles.

For more information, see the memory manage section of the Core Data Programing Guide.

Also, just as a note, if you're sending instances of managed objects across threads, you shouldn't be. You should use the object id instead (these are thread safe).

Jason Coco