views:

518

answers:

1

Hi, this is a follow up forr http://stackoverflow.com/questions/1552944/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

+1  A: 

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.

Thomas Müller
Thank you. What I have something like this declaration:NSString *foo;Should I also do this:foo = [NSString initWithFormat: @"Hello %d", i]orfoo = [[[NSString alloc] initWithFormat:@"Hello %d", i] autorelease]Now I have this:foo = [[NSString alloc] initWithFormat: @"Hello %d", d];...[foo release]
leon
TRYING TO FIX FORMATTING.... Thank you. What I have something like this declaration: NSString *foo; Should I also do this: <pre>foo = [NSString initWithFormat: @"Hello %d", i] or foo = [[[NSString alloc] initWithFormat:@"Hello %d", i] autorelease] Now I have this:foo = [[NSString alloc] initWithFormat: @"Hello %d", d]; ... [foo release] </pre>
leon