简体   繁体   English

方法是否在Objective-C中保留参数?

[英]Do methods retain arguments in Objective-C?

Do methods retain the arguments that are passed? 方法是否保留传递的参数? If so, can I release these arguments in the next line? 如果是这样,我可以在下一行释放这些参数吗? And if not, then when do I release these objects (in case I am allocating these locally)? 如果没有,那我什么时候释放这些对象(以防我在本地分配这些对象)?

The language will not retain arguments automatically. 语言不会自动保留参数。 However, code that obeys the rules will retain or copy anything that it needs to keep around after execution leaves its scope. 但是,遵守规则的代码将在执行离开范围后保留或复制需要保留的所有内容。

In other words: 换一种说法:

id object = [[SomeClass alloc] init];
[otherObject doSomethingWithObject:object];
[object release];

This code should always be OK, because if doSomethingWithObject: needs to keep its argument around, it will send it retain , and if it doesn't, it won't. 该代码应始终是好的,因为如果doSomethingWithObject:需要保持它的参数周围,它会发出它retain ,如果没有,也不会。

No, they simply handle the object, they don't control the memory. 不,他们只是处理对象,不控制内存。

You should release something in the method it was created. 您应该使用创建方法释放一些内容。 Or, if it's a property or an ivar, you should release it in the dealloc (if it is retained). 或者,如果它是属性或ivar,则应在dealloc中释放它(如果已保留)。

Methods do not increment the reference count. 方法不增加引用计数。 However if you assign it to a variable with retain count then you need to explicitly send a nil message to both. 但是,如果将其分配给具有保留计数的变量,则需要向两者显式发送一条nil消息。 Release of a variable can be done when you no longer want to use it. 当您不再想要使用变量时,可以完成释放。 So a allocated variable will have its reference count incremented whenever a retain message is sent to it. 因此,每当发送保留消息时,分配的变量的引用计数就会增加。 So you need to send equal number of release messages till reference count becomes zero. 因此,您需要发送相等数量的释放消息,直到引用计数变为零为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM