简体   繁体   中英

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.

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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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