iPhone SDK - 使用 performSelectorInBackground 泄漏内存 [英] IPhone SDK - Leaking Memory with performSelectorInBackground

查看:19
本文介绍了iPhone SDK - 使用 performSelectorInBackground 泄漏内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许有人可以帮我解决这个奇怪的事情:

Maybe someone can help me with this strange thing:

如果用户点击一个按钮,一个新的 UITableView 会被推送到导航控制器.这个新视图正在执行一些需要一些时间的数据库查询.因此我想在后台进行加载.

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];  

现在我尝试这样做:

    // 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 ?

顺便说一句 - 应用程序是否有可能以少量内存泄漏进入 AppStore?还是会先检查这个?

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 ?

提前致谢!

推荐答案

不,小的内存泄漏不会(很可能)您的应用程序被 appstore 拒绝.

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

在您的示例中,当您在单独的线程中运行您的方法时,您应该为该线程创建和处置 NSAutoreleasePool 对象以处理自动释放的对象.对 getController 方法的以下更改应该可以解决问题:

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];
}

更多详情请参见Autorelease Pools 部分在内存管理指南中.相关引述:

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.)

这篇关于iPhone SDK - 使用 performSelectorInBackground 泄漏内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆