I just wanted to know: will the retain count of an object be incremented if it is added to an array or dictionary in Objective-C? Can I release a particular object immediately after adding it to an array or dictionary?
-
1You could easily answer that yourself (and probably quicker) if you actually bothered to read the documentation!– SvenApr 14, 2011 at 10:54
-
@Sven:i read the documentation but as i am new to this plat form i would like to know it very clearly i had some doubt before, now it is clear.– HariprasadApr 14, 2011 at 11:07
-
@joe Blow: i completely support you in this regard joe... This kind of behavior would be discouraging for the new users to get into stackoverflow....– A for AlphaApr 15, 2011 at 5:56
3 Answers
Yes, it will increase the retain count of the object you added, that is why you can release the object immediately after adding it to the array.
NSObject obj1;
obj1=[[NSObject alloc] init];
//obj1's retain count is 1 here.
[array1 addobject:obj1];
//obj1's retain count incremented by 1, so the total retain count is 2.
[obj1 release];
//obj1's retain count decremented by 1, so the total retain count is 1.
array1
will keep the object until the array1 itself is not released.
Hariprasad,
NS[collection name here] retain objects added to them as NSResponder noted. A few other facts:
- To your comment "can I release it
after adding", the short answer is
yes. Often times I do an
autorelease
for objects that are bound for containment in a collection and won't be needed outside the collection. - When you remove an object from a collection, the reference count is decremented. If you want to ensure it won't be deleted from memory (next pool sweep) you need to retain the object.
-
For your point 2, autorelease pools are not involved when it comes to addition and removal from a collection. The objects are immediately retained and released, and if nothing else has retained the object at the time it is removed from a collection, it will be deallocated at that moment, not at a later time.– Brad Larson ♦Apr 14, 2011 at 16:58
-
@Brad... for point 2 I didn't say anything about autorelease pool. The rest of your comment is restating the same thing I said at that point.– Frank C.Apr 14, 2011 at 21:56
NSArrays retain any object added to them.
-
-
1All the standard Cocoa containers retain objects added to them. That means you can release them right away, if you don’t plan to hold another reference to them. You really should read Apple’s memory management guide.– SvenApr 14, 2011 at 10:53