the cause of the delegate why use assign

delegate使用方法:

@property (assign) <id>xxxDelegate delegate;

正确的使用方法是使用assign属性而不是retain。援引stackoverflow查到的东西:

"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."

这段话比较好懂,assign属性直接给实例变量赋值,而不是将引用计数加一。最适合于原始类型如:int,float,和一些你不直接拥有的对象,如:delegates

之所以对于delegate这类对象使用assign而不是用retain是为了防止循环retain(retain loop),retain delegate会引起循环retain是因为:

A creates B A sets itself as B's delegate. A is released by its owner. If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.(这段话反复理解一下,刚开始我也没看懂。)

上面介绍了为什么使用assign而不是retain定义一个delegate,其原因是为了避免retain loop,再说下retain loop是怎么回事:

Retaining an object creates a strong reference(强引用), and an object cannot be deallocated until all of its strong references are released. If two objects retain each other, neither object ever gets deallocated because the connection between them cannot be broken。

demo:

  1. @class ABC

    @interface ABC : NSObject
    {
        int serial;
        ABC *x;
    }

    @property (retain) ABC *x;
    @property int serial;

    @end

    @implementation ABC
    @synthesize x;
    @synthesize serial;

    -(id) init
    {
        if ( self = [super init] ) {
            serial=0;
            x=nil;
        }
        return self;
    }

    -(void) dealloc
    {
        NSLog(@"ABC dealloc, serial: %d",serial);
        [x release];
        [super dealloc];
    }




测试代码:
复制代码

  1. void test(void)
    {
        ABC *a=[[ABC alloc] init];
        a.serial=1;
        ABC *b=[[ABC alloc] init];
        b.serial=2;

        a.x=b;
        b.x=a;
        
        [b release];    
        [a release];
    }



运行结果:dealloc不会被调用
a和b没有机会被释放

问题在于property用了retain

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值