Delegates - retain or assign - release?

前端 未结 3 972
别那么骄傲
别那么骄傲 2020-12-17 16:23

I\'ve seen a number of posts related to delegates, and I would like to know the proper way to reference them. Suppose I have an object declared like:

@inter         


        
3条回答
  •  死守一世寂寞
    2020-12-17 16:41

    You generally want to assign delegates rather than retain them, in order to avoid circular retain counts where object A retains object B and object B retains object A. (You might see this referred to as keeping a "weak reference" to the delegate.) For example, consider the following common pattern:

    -(void)someMethod {
        self.utilityObject = [[[Bar alloc] init] autorelease];
        self.utilityObject.delegate = self;
        [self.utilityObject doSomeWork];
    }
    

    if the utilityObject and delegate properties are both declared using retain, then self now retains self.utilityObject and self.utilityObject retains self.

    See Why are Objective-C delegates usually given the property assign instead of retain? for more on this.

    If you assign the delegate rather than retaining it then you don't need to worry about releasing it in dealloc.

提交回复
热议问题