开发者

objective c - memory managment

lets say I have aclass

@interface Foo :NSobject  
{  
  NSstring *a;  
  NSDate *b;  
}  
Foo *temp; 开发者_StackOverflow社区 

my question is: when i use [temp retain] does the counter of the members also retain? lets say that i got ref of the class from some method and i want to retain the class do i need to retain each member?


when i use [temp retain] does the counter of the members also retain?

No.

lets say that i got ref of the class from some method and i want to retain the class do i need to retain each member?

No.

The members' lifetime should be managed by the Foo class itself, not the user of the Foo class. If you can/need to change the retain count of the members, the class is not properly encapsulated.


No, calling [temp retain] will not retain a and b. The typical pattern that you'll see is that a and b are retained in the -init method of the class and released in the -dealloc method, which keeps them around as long as the object is. For example:

@implementation Foo

- ( id)initWithA:( NSString * )aString andB:( NSString * )bString
{
    if ( self = [ super init ]) {
        a = [ aString copyWithZone:[ self zone ]];
        b = [ bString copyWithZone:[ self zone ]];
    }

    return self;
}

- ( void )dealloc
{
    [ a release ];
    [ b release ];

    [ super dealloc ];
}

@end

In this example, a and b are automatically retained as a result of the -copyWithZone: call. You don't need to retain them yourself.


Eimantas,

You could assume so if you are using Garbage Collection. As you did not specify an iPhone app I will guess you are talking about a OS X app and the question then remains are you building for Leopard or above?

Frank

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜