views:

590

answers:

1

Hi. Maybe someone can help me with this strange thing:

If a user clicks on a button, a new UITableView is pushed to the navigation controller. This new view is doing some database querying which takes some time. Therefore I wanted to do the loading in background.

What works WITHOUT leaking memory (but freezes the screen until everything is done):

WorkController *tmp=[[WorkController alloc] initWithStyle:UITableViewStyleGrouped];
self.workController=tmp;
[tmp release];

[self.workController loadList]; // Does the DB Query
[self.workController pushViewController:self.workController animated:YES];  

Now I tried to do this:

    // Show Wait indicator
    ....

    WorkController *tmp=[[WorkController alloc] initWithStyle:UITableViewStyleGrouped];
    self.workController=tmp;
    [tmp release];

    [self performSelectorInBackground:@selector(getController) withObject:nil];
}

-(void) getController {
    [self.workController loadList]; // Does the DB Query
    [self.navigationController pushViewController:self.workController animated:YES];
}

This also works but is leaking memory and I don't know why ! Can you help ?

By the way - is it possible for an App to get into AppStore with a small memory leak ? Or will this be checked first of all ?

Thanks in advance !

+2  A: 

No, small memory leaks will not (most likely) you application to be rejected from appstore.

In your example as you run your method in separate thread you should create and dispose NSAutoreleasePool object for that thread to handle autoreleased objects. Following changes to getController method should do the trick:

-(void) getController {
    NSAutoreleasedPool *pool = [[NSAutoreleasedPool alloc] init];

    [self.workController loadList]; // Does the DB Query
    [self.navigationController pushViewController:self.workController animated:YES];

    [pool release];
}

For more details see Autorelease Pools section in memory management guide. Relevant quote from there:

If you spawn a secondary thread, you must create your own autorelease pool as soon as the thread begins executing; otherwise, you will leak objects. (See “Autorelease Pools and Threads” for details.)

Vladimir
First of all - thanks for your reply. But where is the NSAutorelease Pool used ? Isn't it just allocated and released ?
Steblo
Thanks ! Using pool did the trick. It works now without leaking (and it IS possible to push a view to stack in background thread)
Steblo
NSAutoreleasePool handles autoreleased objects and make sure that they will be actually released. Although you it looks like you just create and release it it does a lot of work.
Vladimir