Q.1 - Does this increase retain count?? i think it's not
Not necessarily, but it might increase it temporarily. The implementation of objectAtIndex:
could retain
and then autorelease
the object before returning it, and that would be a very friendly thing to do in light of...
Q.2 - So now object1 point to deallocated instance?? and if i send message to it will it crash??
It might, if -objectAtIndex:
didn't take care to return an autoreleased object as described above. If there's any doubt, you should retain the object yourself before removing it from the container. So, for example, the documentation for -[UIView removeFromSuperView]
says:
If you plan to reuse a view, be sure to retain it before calling this method and release it again later as appropriate.
That's exactly because the superview will release the view. If you haven't retained it, it may be deallocated at that point.
So i should use ClassA object1 = [[ClassAObjectContainer objectAtIndex:0] retain]; if i want to keep the object alive and use it later.
Certainly you should retain it if you want to use it "later". If you're going to use it "now" then you may not need to retain the object, depending (again) on what ClassAObjectContainer
says it does.
I'm not sure I follow the rest of your question. Generally, though, when you get an object back from some other method, you should be able to use that object without retaining it unless you plan to keep it around beyond the end of the method in which you received it. So, if you're assigning it to an instance variable or something, you should take ownership of the object by calling retain
. The behavior of a collection complicates things a little -- if you get an object from a collection and then tell that collection to remove the object, you really should expect to have to retain the object first if you'll need it after it's been removed. On the other hand, if you use ARC (and why wouldn't you?), you don't have to worry about such things.