CoreData completion handler memory leak

Hi,


I am using CoreData, and using blocks with completion handlers to pass the feched object to my viewcontroller.


I am having a problem with a constant slow memory build up, and I found where it is coming but not sure how to fix it.

Here is my fetchrequest:


- (void)sr_executeFetchRequest:(NSFetchRequest *)request completion:(void (^)(NSArray *objects, NSError *error))completion {

__block NSManagedObjectContext *weakSelf = self;


[weakSelf performBlock:^{

/

NSError *error = nil;

NSArray *fetchedObjects = [weakSelf executeFetchRequest:request error:&error];

[weakSelf performBlock:^{

if (fetchedObjects) {

/

NSMutableArray *mutObjectIds = [[[NSMutableArray alloc] initWithCapacity:[fetchedObjects count]] autorelease];

for (NSManagedObject *obj in fetchedObjects) {

[mutObjectIds addObject:obj.objectID];

}

/

NSMutableArray *mutObjects = [[[NSMutableArray alloc] initWithCapacity:[mutObjectIds count]] autorelease];

for (NSManagedObjectID *objectID in mutObjectIds) {

NSManagedObject *obj = [weakSelf objectWithID:objectID];

[mutObjects addObject:obj];

}

if (completion) {

NSArray *objects = [mutObjects copy];

completion(objects, nil);

}

} else {

if (completion) {

completion(nil, error);

}

}

}];

}];


}






Note the [mutObjects copy];


If I comment this out to be nil, then my memory doesn't increase, so I know this is the problem.


However, when you don't use copy, or use autorelease (I am not using ARC in this project).. then the code crashes at the fetchrequest.


Any ideas or advice?


Thanks

if (completion) {

NSArray *objects = [mutObjects copy];

completion(objects, nil);

// Add release statement here.

}


You have a memory leak because -copy returns an array with a positive release count that you have to add a corresponding -release or -autorelease in your code when you're done with the object.


Follow up points:

  • Have you been ignoring the static analyzer?
  • You have a variable named "weakSelf" contained in code that isn't using ARC. Why?
  • You're not using ARC. ARC exists because people got tired of explaining to other people what they were doing wrong with their memory management code.

When I do NSArray *objects = [[mutObjects copy] autorelease];

the code crashes.


If I don't copy, it loses the object and crashes as well.


I'm not sure how to pass the variable across the completion handler and release it later, it seems to stay there?


I was doing weakself as a test there I thought it was keeping the performblock with a retain count of self but that didn't help either.

CoreData completion handler memory leak
 
 
Q