views:

145

answers:

2

Hi , i m new to iPhone programming. i am very confused... plz help .. i have a list of questions.

1.

- (void){
  ClassOne *ob = [[ClassOne alloc] init]; // do i should use autorelease here ?
  self.O = ob;
   [ob release]; // is this correct ??
}

or

-(void)dealloc{
 [O release]; // is this correct ??
}

which one will release ob ??? ...

  1. there are two classes suppose ClassOne and ClassTwo .. the method in ClassTwo is this

    • (void) takeParam:(ClassOne *pt) { // something going here }

and there is method in a third class

- (void) runIt {
   ClassOne *ob = [[ClassOne alloc] init];
   [classTwoOb takeParam:ob];
}

in this scenerio where i will call release for ClassOne object ???

+3  A: 

The -release method only reduces the retain count of the object in question. When the retain count reaches zero, the runtime will call -dealloc.

If at any time you send an alloc, copy, or retain message you must later call release or autorelease.

For more details see this excellent answer.

rpetrich
+2  A: 

Number 1 is probably correct.

ClassOne *ob = [[ClassOne alloc] init]; // do i should use autorelease here ?

When you call [ClassOne alloc] you get an object with a retain count of 1 and you are responsible for the release.

self.O = ob;

Assuming self.O is a retain property and not an assign property, self.O/ob will have a retain count of 2.

[ob release];

Now self.O/ob will have a retain count of 1. This release matches up with the alloc. The remaining retain count is owned by self so you'll have to remember to release O when self is finished with it.

-(void)dealloc{
    [O release]; // is this correct ??
}

Good. You remembered to release O. Now O will be fully released when self is dealloced. (Note: you should call [super dealloc] at the end of dealloc.)

- (void) runIt {
   ClassOne *ob = [[ClassOne alloc] init];
   [classTwoOb takeParam:ob];
}

You should release ob after calling takeParam:. Methods are responsible for retaining objects they want to keep. If takeParam: stores ob on classTwoOb, it should be retained before the method returns. If not, it shouldn't.

Use autorelease in methods that return objects that they have created. This gives the caller a chance to retain the object if it wants it, or not if doesn't need it for long. The exception to this is methods used to create objects, which should always be called alloc, new, or *copy*, and should return the object with a reference count of 1, making the caller responsible for the release.

To really learn Objective-C memory management, I recommend reading the Memory Management Programming Guide, especially the section on Memory Management Rules.

Will Harris