释放和自动释放之间有什么区别? [英] What is the difference between releasing and autoreleasing?

查看:167
本文介绍了释放和自动释放之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于发布和自动发布,我仍然不清楚.两者之间有什么区别?我有这个代码.对于Facebook连接.有时我登录Facebook时会崩溃,我怀疑这可能是因为我没有很好地释放该对象.谢谢您的帮助

I still have some unclear understand about release and autorelease. What are the difference between both of them? I have this code. For facebook connection. I crash it sometimes when I go to Facebook login, I doubting maybe it is because I don't release the object nicely.? Thanks for any helps

if (_session.isConnected) {
        [_session logout];
    } else {
        FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:_session] autorelease];
        [dialog show];
    }

推荐答案

-release消息来释放这种兴趣.如果拥有对象保留"和所有权权益的对象数量下降到0(即,当拥有的最后一个实例发送-release消息时),则保留计数为0的实例将被释放.

The Memory Management Programming Guide for Cocoa will soon be your best friend. In brief, object instances in Cocoa are memory managed using reference counting (unless, of course you're using garbage collection on OS X). An object indicates that it wants to 'retain' an ownership interest in an other instance--keep it from being deallocated--by sending it a -retain message. An object indicates that it wants to release that interest by sending the other instance a -release message. If the number of objects that have 'retained' and ownership interest in an object drops to 0 (i.e. when the last of the owning instances sends a -release message), the instance with a 0 retain count is deallocated.

有时候说我希望这个实例在将来的某个时间被释放"是很方便的.这就是-autorelease的目的.发送-autorelease消息会将接收者添加到当前的NSAutoreleasePool中.当该池耗尽时,它将向池中的所有实例发送-release消息. NSAutoreleasePool在每个线程的运行循环的每次迭代开始时自动创建,并在该迭代结束时耗尽.因此,您可以在方法中执行以下操作:

It's sometimes convenient to say "I want this instance to be released some time in the future". That's the purpose of -autorelease. Sending an -autorelease message adds the receiver to the current NSAutoreleasePool. When that pool is drained, it sends a -release message to all the instances in the pool. An NSAutoreleasePool is automatically created at the start of each iteration of each thread's run loop and drained at the end of that iteration. Thus, you can do something like this in a method:

- (id)myMethod {
  return [[[MyObject alloc] init] autorelease];
}

此方法的调用者将返回一个实例,如果他们希望保留该实例,则可以-retain.如果他们不保留它,它将至少缠住直到封闭的自动释放池耗尽:

The caller of this method will get back an instance that they can -retain if they wish to keep it. If they don't retain it, it will stick around at least until the enclosing autorelease pool is drained:

- (void)someOtherMethod {
...

id instance = [obj myMethod];
... // do more with instance, knowing that it won't be dealloc'd until after someOtherMethod returns

}

这篇关于释放和自动释放之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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