简体   繁体   中英

concept of retain in objective c

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];
}

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.

尝试这篇针对Java程序员的Objective-C入门文章,它可以很好地解释这一点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM