i am new in objective c.....i am aware of alloc and release..... but dont know when and why to use retain statement...... please help....need just basic idea...
please also tell something about copy statement.....
i am new in objective c.....i am aware of alloc and release..... but dont know when and why to use retain statement...... please help....need just basic idea...
please also tell something about copy statement.....
retain
is the opposite of release
, instead of decreasing the reference counter it increases it by one. When you remove an object from an NSArray you usually have to retain
as removing it will cause release
to be called on that object. retain is used when you store a reference to an object as an instance variable in one of your classes. If you are using properties most retain
calls will be done automatically for you.
What is important for correct memory management is that for each retain
there needs to be a release
or you will create a memory leak.
@property (retain) NSNumber* input;
Would generate:
- (void) setInput: (NSNumber*)input
{
[input autorelease];
input= [input retain];
}
You should read this : http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
Try this Objective-C introductory article for Java programmers which does a good job at explaining this.
The concept of retain
is the exact meaning of the English word; you want the object to stick around.
By conventions almost all objects you get access to, be it return values or your method argument, are autoreleased. Which means that they will be "garbage collected" sometime later, where "sometime later" is shortly after the current method exits.
So if you want to have the object sticking around even after the current method exits, then you need to retain
the object. All objects you ever get access to are autoreleased and will go away, unless you explicitly call retain
, or got them from a method containing any of these words:
alloc
copy
new
These three words in a method name implies a retain
. Example of two retained objects:
Foo* foo = [[Foo alloc] init];
Foo* bar = [foo copy];
Example of who objects that are not retained:
Foo* foo = [Foo fooWithInt:42];
Bar* bar = foo.bar;
release
is the opposite, is means; "I no longer need the object and it can be discared immediately".
autorlease
is a bit more lenient and means; "I no longer need the object, but keep it around for a while in case anyone wants to retain it". You should always autorelease all return values from your own methods.