Amir
Amir

Reputation: 455

objective c - memory managment

lets say I have aclass

@interface Foo :NSobject  
{  
  NSstring *a;  
  NSDate *b;  
}  
Foo *temp;  

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?

Upvotes: 0

Views: 70

Answers (3)

Frank C.
Frank C.

Reputation: 8088

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

Upvotes: 0

Jeff Kelley
Jeff Kelley

Reputation: 19071

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.

Upvotes: 0

kennytm
kennytm

Reputation: 523224

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.

Upvotes: 2

Related Questions