Sql – iPhone SDK: loading UITableView from SQLite – creating array from SQLite

iphoneobjective-c-2.0retainsqlite

this is a follow up forr iPhone SDK: loading UITableView from SQLite

I am planning to use following code to load SQL data to the array. Each element of the array will be a class represening each database entry:

@interface Row : NSObject {
int PK;
NSString *desc;

}

@property int PK;
@property (nonatomic, retain) NSString *desc;

@end

the loading operation will be similar to this:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];
Row *myRow = [[Row alloc] init];


for (int i=0; i<10; i++)
{
    myRow.PK = i;
    myRow.desc = [[NSString alloc] initWithFormat:@"Hello: %d", i];
    [array addObject:myRow];
}
[myRow release];

for (int i=0; i < [array count]; i++)
{
    Row *myNrow = [array objectAtIndex:i] ;
    NSLog (@"%@ %d", [myNrow desc], [myNrow PK]);
    myNrow = nil;
}

Of course first for loop will be a loop from SELECT statement. The other loop (or elements of that loop) will be in the cellInRowIndex method to render data.

I have a question about memory leaks. Does the code above have memory leaks? The decs string property of the Row class is declared as (retain). SHould not it be released somewhere?

Thanks

Best Answer

You should release the string that you're putting into myRow.desc. You could change

myRow.desc = [[NSString alloc] initWithFormat:@"Hello: %d", i];

to either

myRow.desc = [[[NSString alloc] initWithFormat:@"Hello: %d", i] autorelease];

or

myRow.desc = [NSString stringWithFormat:@"Hello: %d", i];

EDIT: If you want to use an intermediate NSString (as you mentioned in the comment), you could either do it like this:

NSString *foo = [[NSString alloc] initWithFormat:@"Hello: %d", i];
myRow.desc = foo;
[foo release];

or:

NSString *foo = [NSString stringWithFormat:@"Hello: %d", i];
myRow.desc = foo;

Note that in the second example foo is already autoreleased, so you mustn't release it.

Related Topic