Memory leak in NSMutableArray allocation - objective-c

I am getting memory leak in NSMutableArray allocation.. in
NSMutableArray *contactsArray =[[NSMutableArray alloc] init];
CODE:
+(NSMutableArray*)getContacts
{
addressBook = ABAddressBookCreate();
NSArray* peopleArray = (NSArray*) ABAddressBookCopyArrayOfAllPeople(addressBook);
int noOfPeople = [peopleArray count];
NSMutableArray *contactsArray =[[NSMutableArray alloc] init];
for ( int i = 0; i < noOfPeople; i++)
{
ABRecordRef person = [peopleArray objectAtIndex:i];
ABRecordID personId = ABRecordGetRecordID(person);
NSString* personIdStr = [NSString stringWithFormat:#"%d", personId];
ContactDTO* contactDTO = [AddressBookUtil getContactDTOForId:personIdStr];
[contactsArray addObject:contactDTO];
}
[peopleArray release];
return contactsArray;
}

It is standard procedure that objects returned from methods (in your case, contactsArray) are autoreleased before returning.
You could either return [contactsArray autorelease]; or create it already autoreleased with [NSMutableArray arrayWithCapacity:noOfPeople]

You need to release contactsArray manually somewhere, because it does not define autorelease.

Related

Memory leak while handling Foundation Object from NSJSONSerialization

I'm struggling to fix a memory leak in a helper function I have made. The helper function takes the result of
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError * _Nullable *)error
and converts all the leaf elements into NSStrings if they are NSNumbers.
Here is the method:
-(NSArray *) stringisizeObjects:(NSArray *)inputArray{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *mutable = [[NSMutableArray alloc] initWithCapacity:[inputArray count]];
for (int i = 0; i < [inputArray count]; i++) {
NSArray *keys = [inputArray[i] allKeys];
NSMutableDictionary *addDictionary = [[NSMutableDictionary alloc] initWithCapacity:[keys count]];
for (int j = 0; j < [keys count]; j++) {
id theObject = [[inputArray[i] objectForKey:keys[j]]autorelease];
if ([theObject isKindOfClass:[NSNumber class]]) {
[addDictionary setObject:[theObject stringValue] forKey:keys[j]];
[theObject release];
}else if ([theObject isKindOfClass:[NSString class]]){
[addDictionary setObject:[inputArray[i] objectForKey:keys[j]] forKey:keys[j]];
}
}
[mutable addObject:addDictionary];
}
NSArray *returnArray = [mutable copy];
[mutable removeAllObjects];
[mutable release];
[pool drain];
return returnArray;
}
Here is how I get the input array.
id parsedThingy = [NSJSONSerialization JSONObjectWithData:resultJSONData options:1 error:&jsonDecodeError];
Before I can pass the result to my stringisize method I must ensure that I have an NSArray of NSDictionaries with matching keys.
NSArray *resultArray = [self stringisizeObjects:parsedThingy];
The X-Code memory leaks tool has pointed me to this method as the cause of my problem.
Instruments showing leaks
As you can see I have tried wrapping things in autorelease pools, autoreleasing and releasing. I just don't see any way forward here.
This is a non ARC project that runs 24/7.
Edit: I took the advice from Droppy and tried to re-write the method using mutableCopy. The leak is still there. At this point my only work around maybe to change the source of the JSON to send only strings. :(
-(NSArray *) stringisizeObjects2:(NSArray *)inputArray{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *mutableArray = [inputArray mutableCopy];
for (int i = 0; i < [mutableArray count]; i++) {
NSMutableDictionary *mutableDict = [mutableArray[i] mutableCopy];
NSArray *keys = [mutableDict allKeys];
for (int j = 0; j < [keys count]; j++) {
if ([[mutableDict objectForKey:keys[j]] isKindOfClass:[NSNumber class]]) {
NSString *stringValue = [[mutableDict objectForKey:keys[j]] stringValue];
[mutableDict removeObjectForKey:keys[j]];
[mutableDict setObject:stringValue forKey:keys[j]];
}
}
mutableArray[i] = [mutableDict copy];
[mutableDict release];
}
NSArray *returnArray = [mutableArray copy];
[mutableArray release];
[pool drain];
return returnArray;
}
problem:
addDictionary called alloc but not call release or autorelease
returnArray = [mutable copy]; // did increase retainCount +1, need autorelease here
id theObject = [inputArray[i] objectForKey:keys[j]]; // not need autorelease or release for object that You not own
add NSAutoreleasePool to top an bottom here just do nothing
solution:
-(NSArray *) stringisizeObjects:(NSArray *)inputArray{
NSMutableArray *mutable = [[NSMutableArray alloc] initWithCapacity:[inputArray count]];
for (int i = 0; i < [inputArray count]; i++) {
NSArray *keys = [inputArray[i] allKeys];
NSMutableDictionary *addDictionary = [[NSMutableDictionary alloc] initWithCapacity:[keys count]];
for (int j = 0; j < [keys count]; j++) {
id theObject = [inputArray[i] objectForKey:keys[j]]; // not need autorelease
if ([theObject isKindOfClass:[NSNumber class]]) {
[addDictionary setObject:[theObject stringValue] forKey:keys[j]];
//[theObject release]; // not need release value here
}else if ([theObject isKindOfClass:[NSString class]]){
[addDictionary setObject:[inputArray[i] objectForKey:keys[j]] forKey:keys[j]];
}
}
[mutable addObject:addDictionary];
[addDictionary release]; // release after not use
}
NSArray *returnArray = [[[NSArray alloc] initWithArray:mutable] autorelease]; // auto release for return value
[mutable removeAllObjects];
[mutable release];
return returnArray;
}

Why Instruments is showing so many leaks in the following code?

- (NSArray *) makeKeyValueArray: (NSArray *) arr
{
NSMutableArray *result = [[NSMutableArray alloc] init];
for(int i = 0; i < [arr count]; i++)
{
[result addObject:[[KeyValue alloc] initWithData:[arr objectAtIndex:i] :[arr objectAtIndex:i]]];
}
return result;
}
Instruments is showing 188 leaks in the above code, why is that? can anyone please explain it to me?
- (NSArray *) makeKeyValueArray: (NSArray *) arr
{
NSMutableArray *result = [[NSMutableArray alloc] init];
for(int i = 0; i < [arr count]; i++)
{
id obj = [[KeyValue alloc] initWithData:[arr objectAtIndex:i] :[arr objectAtIndex:i]]; // obj reference count is now 1, you are the owner
[result addObject:obj]; //reference count is now 2, the array is also an owner as well as you.
[obj release];// reference count is now 1, you are not the owner anymore
}
return [result autorelease];
}
Take a look at Basic Memory Management Rules
you must relinquish ownership of an object you own

How to release object of another class in our class?

I have created two classes (FirstClass and SecondClass) in command line application. I created an object of SecondClass in FirstClass method. Now I want to call that method in main and release the memory allocated to that object. My code is as follows..
#implementation FirstClass
+(NSMutableArray *) addObject{
NSMutableArray *namesArray = [[[NSMutableArray alloc]init] autorelease];
SecondClass *second = [[SecondClass alloc]init];
NSLog(#"Before adding object, count = %ld ",[second retainCount]); //RC = 1
[second setName:#"Mobicule"];
[namesArray addObject:second];
NSLog(#"First object addeded, count = %ld ",[second retainCount]); //RC = 2
[second release];
NSLog(#"After release, count = %ld",[second retainCount]); //RC = 1
return namesArray;
}
#end
I want to make retain count to zero..
And main function is as follows..
int main (int argc, const char * argv[]) {
#autoreleasepool {
// insert code here...
// NSLog(#"Hello, World!");
NSMutableArray *arrayMain = [[NSMutableArray alloc]init];
arrayMain = [FirstClass addObject];
for (int i = 0; i<[arrayMain count]; i++) {
NSLog(#"%#",[[arrayMain objectAtIndex:i] name]);
}
NSLog(#"%ld",[arrayMain retainCount]);
}
return 0;
}
I am assuming your synthesised property for name is retain.
+(NSMutableArray *) addObject{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *namesArray = [[NSMutableArray alloc]init];
SecondClass *second = [[[SecondClass alloc]init]autorelease];
NSLog(#"Before adding object, count = %ld ",[second retainCount]); //RC = 1
[second setName:#"Mobicule"]; //implementation will handle the release for you
[namesArray addObject:second];
NSLog(#"First object addeded, count = %ld ",[second retainCount]); //RC = 2
[pool release];
NSLog(#"After pool release, count = %ld",[second retainCount]); //RC=1
return [namesArray autorelease];
}
You should never use -retainCount, because it never tells you anything
useful.
Take a look at When to use -retainCount?

releasing a NSMutableArray is causing EXC_BAD_ACCESS error

so when i try to run the following code, i end up with a EXC_BAD_ACCESS error. it happens when i try to release a NSMutableArray retrievedAnalysisDataList. the array is a list of retrievedAnalysisData objects. if i try to either release the data list or if i set up the init with an autorelease, i get the same result. i'm kinda guessing it has something to do with the sorting section of the code since i don't have this issue with the retrievedAnalysisIDarray.
any ideas?
if (tempDict != NULL)
{
NSMutableArray *retrievedAnalysisDataList = [[NSMutableArray alloc] init];
NSMutableArray *retrievedAnalysisIDarray = [[NSMutableArray alloc] init];
for (id key in tempDict)
{
retrievedAnalysisData = [[RetrievedAnalysisData alloc] init];
retrievedAnalysisData.createDate = [[tempDict objectForKey:key] objectForKey:#"createdate"];
retrievedAnalysisData.ID = [[tempDict objectForKey:key] objectForKey:#"id"];
retrievedAnalysisData.mode = [[tempDict objectForKey:key] objectForKey:#"mode"];
retrievedAnalysisData.name = [[tempDict objectForKey:key] objectForKey:#"name"];
retrievedAnalysisData.numZones = [[tempDict objectForKey:key] objectForKey:#"numzones"];
retrievedAnalysisData.srcImg = [[tempDict objectForKey:key] objectForKey:#"srcimg"];
retrievedAnalysisData.type = [[tempDict objectForKey:key] objectForKey:#"type"];
//NSLog(#"\n createDate: %# \n id: %# \n mode: %# \n name: %# \n numzone: %# \n srcimg: %# \n type: %#", retrievedAnalysisData.createDate, retrievedAnalysisData.ID, retrievedAnalysisData.mode, retrievedAnalysisData.name, retrievedAnalysisData.numZones, retrievedAnalysisData.srcImg, retrievedAnalysisData.type);
[retrievedAnalysisDataList addObject:retrievedAnalysisData];
[retrievedAnalysisData release];
}
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"createDate" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedRetrievedAnalysisDataList;
sortedRetrievedAnalysisDataList = [retrievedAnalysisDataList sortedArrayUsingDescriptors:sortDescriptors];
int count = [sortedRetrievedAnalysisDataList count];
for (int i = 0; i < count; i++) {
retrievedAnalysisData = [[RetrievedAnalysisData alloc] init];
retrievedAnalysisData = [sortedRetrievedAnalysisDataList objectAtIndex:i];
[retrievedAnalysisIDarray addObject:retrievedAnalysisData.ID];
[retrievedAnalysisData release];
}
dataCenter.sortedRetrievedAnalysisDataList = sortedRetrievedAnalysisDataList;
dataCenter.retrievedAnalysisIDarray = retrievedAnalysisIDarray;
[retrievedAnalysisIDarray release];
[retrievedAnalysisDataList release];
dataCenter.isRetrieve = [NSNumber numberWithInt:1];
[activityIndicator stopAnimating];
[picker reloadAllComponents];
picker.hidden = FALSE;
pickerToolBar.hidden = FALSE;
toolBar.hidden = TRUE;
innerCircle.hidden = TRUE;
outerCircle.hidden = TRUE;
trackLabel.hidden = TRUE;
displayGPSLabel.hidden = TRUE;
}
Your problem lies in this section of code:
retrievedAnalysisData = [[RetrievedAnalysisData alloc] init];
retrievedAnalysisData = [sortedRetrievedAnalysisDataList objectAtIndex:i];
[retrievedAnalysisIDarray addObject:retrievedAnalysisData.ID];
[retrievedAnalysisData release];
The first line allocates a new RetrievedAnalysisData, but then the second throws that away (leaking it) and places an object fetched from the array in the retrievedAnalysisData variable instead. You don't own this object fetched from the array, and you don't take ownership by calling retain. So the release on the fourth line is incorrect, releasing an object that you do not own.
Then when you release your NSMutableArray, it tries to release the object again and you get a crash because the object is already released.
To fix it, get rid of the useless first line, and also get rid of the incorrect release.
Without knowing the memory management of all your properties, it’s hard to see exactly what’s going on. But take a look here:
for (int i = 0; i < count; i++) {
retrievedAnalysisData = [[RetrievedAnalysisData alloc] init];
retrievedAnalysisData = [sortedRetrievedAnalysisDataList objectAtIndex:i];
[retrievedAnalysisIDarray addObject:retrievedAnalysisData.ID];
[retrievedAnalysisData release];
}
You call -release on an autoreleased object (retrievedAnalysisData). Try this instead:
for (int i = 0; i < count; i++) {
retrievedAnalysisData = [sortedRetrievedAnalysisDataList objectAtIndex:i];
[retrievedAnalysisIDarray addObject:retrievedAnalysisData.ID];
}

Method Creates an Array with 11 objects, All Out of Scope, Unrecognized Selector Results

Okay, so, I'm doing a simple lookup. I have an array of NSString objects and a string to search for in the array's elements.
It all seems to work up until I try to add a match to a new mutable array made to hold the search results. The stringHolder variable gets the string, and resultsCollectorArray even get the right number of new elements, but each element is empty and "out of range". Here's the method:
#implementation NSArray (checkForString)
-(NSMutableArray *) checkForString: (NSString *) matchSought
{
long unsigned numberofArrayElements;
long unsigned loop = 0;
NSRange searchResults;
NSMutableArray * resultCollectorArray = [[NSMutableSet alloc] init];
id stringHolder;
numberofArrayElements = [self count];
while (loop < numberofArrayElements) {
searchResults.length = 0;
searchResults = [[self objectAtIndex: loop] rangeOfString: matchSought options:NSCaseInsensitiveSearch];
if (searchResults.length > 0) {
stringHolder = [self objectAtIndex: loop];
[resultCollectorArray addObject: stringHolder];
}
loop++;
}
return [resultCollectorArray autorelease];
}
Once we get back to the main portion of the program, I get an unrecognized selector sent to the mutable array that was supposed to receive the result of the method. Here's the main section:
#import <Foundation/Foundation.h>
#import "LookupInArray.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *testString = [[NSString alloc] initWithString: #"ab"];
NSMutableString * resultString = [[NSString alloc] init];
NSArray * theArray = [[NSArray alloc] initWithObjects: ..., nil]; // Actual code has the objects
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSUInteger arrayCount = 0;
unsigned long loops = 0;
resultArray = [theArray checkForString: testString];
arrayCount = [resultArray count];
while (loops < arrayCount){
resultString = [resultArray objectAtIndex: loops]; // Here's where we get the unrecognized selector.
NSLog(#"%#", resultString);
loops++;
}
[pool drain]; // Also, I'll release the objects later. I just want to get what's above working first.
return 0;
}
I've searched the other answers (for hours now), but didn't seen anything that solved the issue.
Any and all help would be really appreciated.
And thanks beforehand.
NSMutableArray * resultCollectorArray = [[NSMutableSet alloc] init]; is so incorrect. You are creating a mutable set and assigning it to a mutable array.
You are getting unrecognized selector because objectAtIndex: is not a valid selector for NSMutableSet. Make that statement,
NSMutableArray * resultCollectorArray = [[NSMutableArray alloc] init];
A Better way
NSArray * filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF contains[cd] %#", searchString]];
You can directly filter the array using predicates. This way you do this in a single step. :)