Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

spaceman816

macrumors member
Original poster
Jul 29, 2009
30
0
Instruments is telling me that mutable array courseNames is leaking, but I can't seem to fix it. Any tips would be greatly appreciated.
code:
Code:
+(NSMutableArray *)selectNamesAndID{

NSString *query = [[NSString alloc] initWithFormat: @"SELECT Name, ID FROM Courses"];

sqlite3_stmt *statement;

NSMutableArray *courseNames = [[NSMutableArray alloc] init];

int result = (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL));

NSString *nameString;

NSString *iDString;

NSArray *tempData;

while(sqlite3_step(statement) == SQLITE_ROW){

char *nameChar = (char *)sqlite3_column_text(statement, 0);

nameString = [NSString stringWithUTF8String:nameChar];

int iDInt  = sqlite3_column_int(statement, 1);

iDString = [NSString stringWithFormat:@"%d", iDInt];

tempData = [NSArray arrayWithObjects:nameString, iDString, nil];

[courseNames  addObject:tempData];

}

sqlite3_finalize(statement);

[query release];

[courseNames autorelease];

return courseNames;

}

and this line of code also:
Code:
currentElementValue = (NSMutableString *)[currentElementValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
 
autorelease

I did autorelease courseNames...it didn't seem to work.
releasing it wouldn't work because it has to be returned.
 
The code you show doesn't return courseNames.

Assuming that you are returning that array then it should be autoreleased and not alloced before returning.

The rule is simple. If you alloc it then release it. (In most cases) return autoreleased objects from methods. If you need an object to hang around for a while, retain it and release it later.
 
The code you show doesn't return courseNames.

Assuming that you are returning that array then it should be autoreleased and not alloced before returning.

The rule is simple. If you alloc it then release it. (In most cases) return autoreleased objects from methods. If you need an object to hang around for a while, retain it and release it later.

I disagree. He's doing the right thing here. This is a method that returns a new array. So of course he has to alloc/init that new array. And he's correctly autoreleasing that new array when he returns it. That much is correct.

I think the root cause of the leak is probably outside of this code, after the array is returned.
 
I dunno if there's any difference or not, but shouldn't it be this?

Code:
return [courseNames autorelease];
 
OK, I take it back. I was mis-reading the code because of a lack of indenting.

The leaks tool doesn't tell you where an object is leaked. It tells you where an object that it determines has leaked was created. The cause of the leak is in some other code.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.