iphone - 适合初学者的自动释放

标签 iphone objective-c cocoa-touch

我发现这个定义非常有用here :

When you autorelease, you're basically saying: "I don't need this any longer, but anyone else is free to pick it up (before the auto release pool is drained)". When you explicitly relase an object you're saying: "I don't need this any longer and unless anyone else has already said otherwise (acquired), it should be deallocated immediately."

Consequently, autorelease is not normally the wrong thing to. It is required when you want to pass objects back to the sender of a message without requiring the sender to take care of releasing the object.

但是,我仍然想知道第二段是什么意思。自动释放通常不是错误的做法...我认为这确实是内存密集型的,所以它自然应该是错误的做法。不过最后一句我恐怕不太明白。

我什么时候真正需要使用自动释放以及初学者可以轻松记住的一个很好的示例/经验法则是什么?

感谢您的任何建议。

最佳答案

Autorelease is not normally the wrong thing to do... I thought it's really memory intensive, so it should naturally be the wrong thing to do.

它根本不是“内存密集型”。如果分配和自动释放大量对象(例如在循环中)或少量大对象,则可能会遇到问题。但是自动释放只是延迟了您正在创建的对象的释放,并且当释放发生时,这些对象可能会也可能不会被释放(自动释放的对象也可能被其他对象保留)。

如果你可以立即释放一个对象,就这样做。如果您需要自动释放,那就这样做,不用担心内存。如果您在循环的每次迭代中创建大量对象,您可能需要考虑使用自己的自动释放池或使用 alloc/init 创建所述对象,以便可以立即释放它们。

But as for the last sentence, I'm afraid I don't get it.

如果一个方法必须在返回之前释放它创建的每个对象,那么在不要求调用者释放返回的对象的情况下就无法返回对象。 Autorelease 允许方法创建一个对象并释放它,但要推迟该释放,直到调用者有机会使用并可能保留返回的对象。

关于iphone - 适合初学者的自动释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5860639/

相关文章:

iphone - UITableView 怪异!带图片

objective-c - NSSet *children = [parentchildren]; 是否执行获取请求?

ios - 在显示VC代码不起作用后删除VC

Iphone实用程序应用程序单例问题

iphone - 有没有办法制作一个仍为 "be there"的不可见 UIButton 并捕获 UIImageView 的触摸事件?

ios - 点击按钮出现错误: unrecognized selector sent to instance - IOS Swift 3

iPhone SDK : Convert MKMapPoint to CGPoint

ios - UIView 图层动画后显示不正确

ios - Cocos2d-x如何创建带有标题和字体的图片按钮

带有半径的 Objective-c 搜索位置