是否有快速规则知道何时发布Objective-C变量?

Rap*_*eta 1 cocoa cocoa-touch memory-management objective-c manual-retain-release

使用Objective-C时是否有任何经验法则可以帮助我了解何时是发布变量的正确时机?

Dav*_*ong 11

NARC!:)

If you invoked a method that contains N ew, A lloc, R etain, or C opy, then you must release or autorelease. Otherwise you don't touch it.

Of course, anything the documentation explicitly says trumps this rule.

The other thing is that when you're dealing with C function the NARC rule still applies, but also gets the Create rule: if the function contains "create", then you're responsible for CFReleasing or freeing the returned data.


Chu*_*uck 6

我强烈建议您多读一遍内存管理规则.它非常短而且不难,一旦你理解了那份文件中的内容,你就不会怀疑.

基本上,将其视为所有权.使用new,copyalloc,或保留对象创建对象时,您拥有该对象.只要拥有所有者,对象就不会消失.当你完成一个对象时,就是release它,从而放弃你的所有权.当对象没有更多所有者时,它可以消失并可能被取消分配.你没有任何对象new,alloc,retaincopy不为你所拥有的,不能保证呆在身边过去的当前呼叫链(即,它是确定使用它,或者返回它,但不要将其存储供以后使用).

  • +1000用于读取内存管理规则。 (2认同)