1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
optimusPrime
  • 249
  • 6
  • 17

3 Answers3

2

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.

benzado
  • 82,288
  • 22
  • 110
  • 138
  • In the above example, Assuming the execution happens sequentially and in case the doSomethingWithObject method does not retain the argument, releasing the object in the next line should never cause a problem ? – optimusPrime Jul 25 '11 at 07:50
  • 1
    @nithin.manu: You are right. Also if the method retains the argument, release here would just decrement the reference count. Hence the retained object also has to be sent a release message. – Praveen S Jul 25 '11 at 08:03
  • So if i alloc,copy,retain an object locally within a function then i should release the object after i pass them as arguments in a method? `code`( - (id) function {
    id object = [[SomeClass alloc] init];// or [someClass copy] or [someClass retain]
    [otherObject doSomethingWithObject:object];
    [object release];
    return otherObject;
    } )
    above statements should not cause any null references and crash my app ?
    – optimusPrime Jul 25 '11 at 09:00
  • A lot has been written about Cocoa memory management. There is plenty to read. See http://stackoverflow.com/questions/156243/object-allocate-and-init-in-objective-c – benzado Jul 25 '11 at 09:18
1

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

Alex Coplan
  • 13,211
  • 19
  • 77
  • 138
0

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.

Praveen S
  • 10,355
  • 2
  • 43
  • 69