james
james

Reputation: 26271

iPhone iOS retrieving NSMutableArray from CoreData using a function

I have a function which returns an NSMutableArray which is fetched from CoreData.

- (NSMutableArray*)getArray:(NSString*)entityName withDescriptor:(NSString*)descriptorKey {
    NSError **error = nil;
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entityDescription];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:descriptorKey ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    return [[managedObjectContext executeFetchRequest:request error:error] mutableCopy];
}

When i Build and Analyze my project containing this function, i get a analyzer result saying that there is a potential leak of an object allocated at line X (the line is where it returns the mutable copy)

I am calling this function like this:

myArray = [self getArray:ENTITY_PAGES withDescriptor:DEFAULT_DESCRIPTOR];

where myArray is a NSMutableArray property of the class, ENTITY_PAGES and DEFAULT_DESCRIPTOR are NSString constants

I wish to use this function in more than one place so i can reduce the amount of redundancy in my project.

How should i populate myArray from Core Data using a function like this without getting these analyzer problems?

Upvotes: 0

Views: 979

Answers (1)

Pete Rossi
Pete Rossi

Reputation: 764

The analyzer is complaining about a potential memory leak because your function is violating one the objective-c memory management rules:

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message.

Change the name of your function appropriately (and make sure you release the returned array at some point) and the analyzer should stop complaining.

Here is the link to the memory management guide:

http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

Upvotes: 2

Related Questions