When you instantiate an object inside a method, when that method is called the object will be allocated memory but what object will hold reference to this object or will it be automatically be deallocated when the method ends. Thanks.
-
I should have been more specific: I am referring to ARC and the object is not an instance variable of the class, just holding info until the method ends, such as the length of a string. So the simple answer here it seems is: 'when it goes out of scope'? – user2909415 Oct 23 '13 at 01:57
3 Answers
In OS X and iOS 5+, Objective-C uses Automatic Reference Counting. In this case, the object is freed when it goes out of scope, just like you'd expect.
Before that, you needed to explicitly retain and release objects. Here's a useful article from 2010 on this topic.
Objective-C in retain count mode (not using garbage collection) is a simple idea. When you explicitly allocate an object it gets a retain count of 1 and when you call release or autorelease on an object it's retain count gets decremented and then the object will be collected. It is the only mode available on iOS Devices and has been in use on Mac OS X since the beginning of the OS.

- 1
- 1

- 8,406
- 24
- 39
Short answer, if you are using ARC (Automatic Retain Count) or if the object is autorelease it will be sent a release
message when appropriate.
If you are manually managing the memory, you have to manually send a release
method to those object whenever they are returned by either new
, alloc
, retain
, copy
or mutableCopy
, otherwise the object will leak as you will be losing any reference to it when the stack gets teared down.

- 106,943
- 21
- 217
- 235
If your application is ARC then it will be dealloc'd after it goes out of scope. If the object is a property of a class then it will be cleaned up by different rules depending on whether it is defined as strong
or weak
. Strong means that the object will not be cleaned up as long as the object that owns it points to it (so as long as the object that owns it exists then it will not be cleaned up). Weak means that the object will not be cleaned up as long as another object points to it.

- 14,627
- 23
- 80
- 126