开发者

Question about Memory Management in iOS

i have a question about memory management.I have an instance variable that I previously allocated in the init* method. In some point in my program, I retained this object. In my dealloc method, if I set this object to nil, will he be correctly deallocated? Let me show an example. This the A.h class :

@interface A: NSObject {
  B *bvariable;
}
-(id) init;

and his implementation :

 @implementation A

  -(id) init: { 
      bvariable= [[B alloc] init];


       /**
        *  Let say for some reason, I called   
       */   
       [bvariable retain];
   }
}

-(void) dealloc {
     bvariable = nil;
     [super dealloc];
}

My question is when the GC will call dealloc on the A cla开发者_JAVA技巧ss, will the bvrariable be properly deallocated?

My guess is no because since i retained this object, so I must call release twice to release that object. Setting an object to nil will not deallocate them since I still send messages to bvrariable object. But someone told me the contrary.

Can someone enlight me plz?

Thanks for your advice !!


My question is when the GC will call dealloc on the A class, will the bvrariable be properly deallocated?

No,

1) GC is not used in iOS memory managent.

2) In dealloc you just set this pointer to nil (quite pointless thing to do in dealloc) - object itself is not released or/and deallocated.

My guess is no because since i retained this object, so I must call release twice to release that object.

Right. BTW I can't see any sane reason to retain this object after alloc - you have already claimed ownership of it.


In general every method that starts with alloc/init/copy/new should return a retained object. If you retain this object again then the retain count is 2. In order to release the object fully you will have to release twice.

The story about releasing an object when you set it to nil is only applicable if you use Garbage Collection (GC). This is currently not available for iOS, just Mac OS.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜