开发者

When to release a class with delegates

A quick question to delegates. Lets say, CLASSA has a delegate defined:

@protocol MyDelegate
   -(void) didFinishUploading;
@end

In CLASSB I create an instance of CLASS A

-(void) doPost { 
    CLASSA *uploader = [[CLASSA alloc] init];
    uploader.delegate = self;  // this means CLASSB has to implement the delegate
    uploader.post; 
}

and also in CLASSB:

-(void)didFinishUp开发者_JS百科loding {
}

So when do I have to release the uploader? Because when I release it in doPost, it is not valid anymore in didFinishUploading.

Thanks


Release it in didFinishUploding. Put CLASSA * uploader in the instance variables of CLASSB to allow for that.


Instead of creating CLASSA instance in doPost method. It is better to create CLASSA *uploader = [[CLASSA alloc] init]; in the init method and release uploader in dealloc.

make uploader as member variable.

    -(id) init
    {
        self = [super init];
        if(self)
        {
          uploader = [[CLASSA alloc] init];
          uploader.delegate = self;

        }
        retrurn self;
    }

    -(void) doPost 
     {
        uploader.post;
     }

   -(void)didFinishUploding
    {
       uploader.delegate = nil;
       //your code
    }

    -(void) dealloc
    {
       [uploader release];
       [super dealloc];
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜