ios 分配释放
我的应用程序收到内存警告,因为它需要大量内存。我尝试释放每一个分配。然而,有时我不知道该怎么做。
例如:我有两对.h和.m文件。其中一个与服务器建立连接,另一个与本地 SQLite 建立连接。
通常,从这些文件调用方法的代码如下:
-(NSMutableArray *) getRecentActivity{
LocalStorageController *local = [[LocalStorageController alloc]init];
return [local getRecentActivity];
}
getRecentActivity 返回一个 NSMutableArray。
好吧,在那段代码中,我们可以看到我正在为 LocalStorageController 分配内存,但我从不调用release方法,所以我想,我调用该函数的次数越多,我分配的内存就越多。
如果我在 init 之后调用 autorelease,它就会崩溃。
此外,通常,我使用其他类型的代码:
ServerConnection *serv = [[ServerConnection alloc]init];
NSMutableArray list = [serv getMyListOfContacts];
它使用 ASIHTTPRequest,如果我在第二行之后调用 [serv release];
,应用程序会崩溃,EXC_BAD_ACCESS 指向 ASIHTTPRequest 库中的一行。
应该如何处理这种情况?
非常感谢!
My app is receiving memory warnings because it's asking for lot of memory. I try to release every allocation. However, sometimes I don't know how to do it.
For example: I have two pairs of .h and .m file. One of them makes connections with a server and the other with local SQLite.
Usually, the code which calls to a method from those files are like this:
-(NSMutableArray *) getRecentActivity{
LocalStorageController *local = [[LocalStorageController alloc]init];
return [local getRecentActivity];
}
getRecentActivity returns a NSMutableArray.
Well, in that piece of code we can see that I am allocating memory for the LocalStorageController but I never call to the release method so, I suppose, the more I call that function, the more memory I will be allocating.
If I call autorelease after init, it will crash.
Moreover, usually, I use this other kind of code:
ServerConnection *serv = [[ServerConnection alloc]init];
NSMutableArray list = [serv getMyListOfContacts];
Which uses ASIHTTPRequest and, if I call [serv release];
after the second line, the app crashes with EXC_BAD_ACCESS pointing to a line in ASIHTTPRequest library.
How is suppose to manage this situation?
Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一种情况很简单;
如果不查看更多实际代码,第二种情况很难以通用方式解决。
The first case is easy;
The second case is hard to solve in a general way without seeing more of the actual code.
使用 serv 作为属性将解决此保留/释放问题。
在你的 .h 中:
在你的 .m 中:
从那时起,只要继续在此类中使用 self.serv ,就不会遇到释放对象的问题。
Using serv as a property would be fixing this retain/release problem.
In your .h:
In your .m:
Just keep on using self.serv in this class from that point on and you won't have a problem with having the object being released.