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];
}
Related
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;
}
I get the "Value stored to 'myKeyArray' during its initialization is never read" message for the marked lines and i do not quite understand why this is happening.
- (void)createAndMigrateStatisticalDataForPlayersToV3 {
NSString *playerStatsfilePath = [self dataFilePath5];
NSString *playerDatafilePath = [self dataFilePath6];
NSArray *myKeyArray = [[NSArray alloc]init]; <<<< "Value stored to 'myKeyArray' during its initialization is never read"
NSMutableArray *theObjects = [[NSMutableArray alloc]init]; <<<< "Value stored to 'myKeyArray' during its initialization is never read"
NSFileManager *fileMgr;
fileMgr = [NSFileManager defaultManager];
if ([fileMgr fileExistsAtPath: playerDatafilePath] == YES) {
NSMutableDictionary *gameFileDict = [NSMutableDictionary dictionaryWithContentsOfFile:playerDatafilePath];
NSMutableArray *dataArray = [[NSMutableArray alloc]init];
NSMutableArray *newDataArray = [[NSMutableArray alloc]init];
myKeyArray = [gameFileDict allKeys];
int nrOfKeys = [myKeyArray count];
for (int oo = 0; oo < nrOfKeys; oo++) {
theObjects = [gameFileDict valueForKey:[myKeyArray objectAtIndex:oo]];
[dataArray addObject:[myKeyArray objectAtIndex:oo]]; // Name
[dataArray addObject:[theObjects objectAtIndex:1]]; // # of games played
[dataArray addObject:[theObjects objectAtIndex:2]]; // # correct answers
[dataArray addObject:[theObjects objectAtIndex:3]]; // # questions
[dataArray addObject:[theObjects objectAtIndex:4]]; // # of games won
[dataArray addObject:[theObjects objectAtIndex:5]]; // # of games lost
}
int dataCount = [dataArray count];
float avgNrOfQuestionsPerGame = 0;
float avgNrCorrectAnswersPerGame = 0;
float nrOfQuestions = 0;
float nrOfCorrectAnswers = 0;
float nrOfGamesPerPlayer = 0;
float nrOfMatchesWonPerPlayer = 0;
float nrOfMatchesLostPerPlayer = 0;
for (int oo = 0; oo < dataCount; oo = oo + 6) {
nrOfGamesPerPlayer = [[dataArray objectAtIndex:oo+1]floatValue];
nrOfCorrectAnswers = [[dataArray objectAtIndex:oo+2]floatValue];
nrOfQuestions = [[dataArray objectAtIndex:oo+3]floatValue];
nrOfMatchesWonPerPlayer = [[dataArray objectAtIndex:oo+4]floatValue];
nrOfMatchesLostPerPlayer = [[dataArray objectAtIndex:oo+5]floatValue];
// nrOfGamesPerPlayer = nrOfMatchesLostPerPlayer + nrOfMatchesLostPerPlayer;
avgNrOfQuestionsPerGame = nrOfQuestions / nrOfGamesPerPlayer;
avgNrCorrectAnswersPerGame = nrOfCorrectAnswers / nrOfGamesPerPlayer;
for (int ff = 0; ff < nrOfGamesPerPlayer; ff++) {
[newDataArray addObject:[dataArray objectAtIndex:oo]]; //PlayerName
[newDataArray addObject:[self get_the_Date]]; //set todays date
[newDataArray addObject:[NSNumber numberWithInt:avgNrOfQuestionsPerGame]];
[newDataArray addObject:[NSNumber numberWithInt:avgNrCorrectAnswersPerGame]];
}
}
[newDataArray writeToFile:playerStatsfilePath atomically: TRUE];
}
I would take this line out, You shouldn't need to initialize it.
//NSArray *myKeyArray = [[NSArray alloc]init];
Change this to
NSArray *myKeyArray;
You only need to allocate it if it is mutable.
You're reassigning both myKeyArray and theObjects after you allocated memory for them, so you have a massive memory leak.
Remove the declarations with the allocations and move the variable declaration to the line where you perform the assignment:
NSArray *myKeyArray = [gameFileDict allKeys];
The same for theObjects:
NSArray *theObjects = [gameFileDict valueForKey:[myKeyArray objectAtIndex:oo]];
Note that you don't have to declare it as NSMutableArray. You're not changing the array.
I'm trying to add objects to a NSMutableArray through a for loop. But it seems whenever I add an object it replaces the old one so that I only have one object in the array at the time...
Do you have any idea of what might be wrong?
- (void)viewDidLoad
{
[super viewDidLoad];
LoginInfo *info = [[LoginInfo alloc] init];
info.startPost = #"0";
info.numberOfPosts = #"10";
info.postType = #"1";
getResults = [backendService getAllPosts:info];
for (NSInteger i = 0; i < [getResults count]; i++) {
Post *postInfo = [[Post alloc] init];
postInfo = [getResults objectAtIndex:i];
dataArray = [[NSMutableArray alloc] init];
[dataArray addObject:postInfo.noteText];
NSLog(#"RESULT TEST %#", dataArray);
}
}
It's the RESULT TEST log that always shows only the last added string in the output.
you are initialising the dataArray inside the for loop, so everytime it is created again (which means there are no objects) and a new object is added
move
dataArray = [[NSMutableArray alloc] init];
to before the for loop
also there is no need to alloc/init the postInfo object when you immediately override it with the object from the getResults array
You keep re-initializing the array for every run of the loop with this line:
dataArray = [[NSMutableArray alloc] init];
So dataArray is set to a new (empty) array for every run of the loop.
Initialize the array before the loop instead. Try something like this:
dataArray = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < [getResults count]; i++) {
PostInfo *postInfo = [getResults objectAtIndex:i];
[dataArray addObject:postInfo.noteText];
NSLog(#"RESULT TEST %#", dataArray);
}
Crash occurs at [searchDict release]. If I switch order of the two latest lines it still crash on the latest line (now [searchArray release]). I'm quite new to Objective C and I guess I haven't got the alloc/release right... Help? :)
NSMutableDictionary *searchDict = [[NSMutableDictionary alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for(int i = 0; i < 2; i++) { // Run two times ("Favorites" and "All")
searchDict = [listOfItems objectAtIndex:i];
searchArray = [searchDict objectForKey:#"Entries"];
for (NSString *sTemp in searchArray) {
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[listOfItemsDynamic addObject:sTemp];
}
}
[searchArray release];
[searchDict release];
You allocate space and assign it to the variables:
NSMutableDictionary *searchDict = [[NSMutableDictionary alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
But then you assign non locally-allocated data to them:
searchDict = [listOfItems objectAtIndex:i];
searchArray = [searchDict objectForKey:#"Entries"];
So basically, you don't need to allocate and release. Instead do something like this:
NSMutableDictionary *searchDict; // Just declartion, no allocation / init
NSMutableArray *searchArray; // Just declartion, no allocation / init
for(int i = 0; i < 2; i++) { // Run two times ("Favorites" and "All")
searchDict = [listOfItems objectAtIndex:i];
searchArray = [searchDict objectForKey:#"Entries"];
for (NSString *sTemp in searchArray) {
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[listOfItemsDynamic addObject:sTemp];
}
}
// No release needed here
If you are familiar with C, it is similar to:
char *pChar;
pChar = malloc(15); // allocate memory and assign to pChar
pChar = "Hello"; // assign new address to pChar
free(pChar); // Error here ;)
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.