Search code examples
iphoneiosobjective-cobjective-c-blocksstackmob

Why is executeFetchRequest:fetchRequest leaking memory?


Instruments shows the following code leaks, if I comment out this code there is no leak.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    // Edit the entity name as appropriate.

    NSEntityDescription *entity = [NSEntityDescription entityForName:USER_CORE_DATA inManagedObjectContext:self.managedObjectContext];

    [fetchRequest setEntity:entity];

    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"username == %@", [[User defaultManager] savedUsername]];
    [fetchRequest setPredicate:predicte];

    // set any predicates or sort descriptors, etc.

    // execute the request
    [self.managedObjectContext executeFetchRequest:fetchRequest onSuccess:^(NSArray *results) {

    } onFailure:^(NSError *error) {

        NSLog(@"Error fetching: %@", error);

    }];
    [fetchRequest release];

Specifically instruments says this line in the code above:

[self.managedObjectContext executeFetchRequest:fetchRequest onSuccess:^(NSArray *results)

It appears to be a leak with fetchRequest and/or the block. Any help will be appreciated, and thanks in advance.


Solution

  • Actually it turned out that StackMob had a leak in their code, I downloaded there source and fixed it.

    - (NSString *)primaryKeyField
    {
        NSString *objectIdField = nil;
    
        // Search for schemanameId
        objectIdField = [[self SMSchema] stringByAppendingFormat:@"Id"];
        if ([[[self entity] propertiesByName] objectForKey:objectIdField] != nil) {
            return objectIdField;
        }
    
        objectIdField = nil;  // This line was missing and causing a leak
    
        // Search for schemaname_id
        objectIdField = [[self SMSchema] stringByAppendingFormat:@"_id"];
        if ([[[self entity] propertiesByName] objectForKey:objectIdField] != nil) {
            return objectIdField;
        }
    
        objectIdField = nil;  // This line was missing and causing a leak
    
        // Raise an exception and return nil
        [NSException raise:SMExceptionIncompatibleObject format:@"No Attribute found for `entity %@ which maps to the primary key on StackMob. The Attribute name should match one of the following formats: lowercasedEntityNameId or lowercasedEntityName_id.  If the managed object subclass for %@ inherits from SMUserManagedObject, meaning it is intended to define user objects, you may return either of the above formats or whatever lowercase string with optional underscores matches the primary key field on StackMob.", [[self entity] name], [[self entity] name]];`