Weak and strong property setter attributes in Objective-C

前端 未结 5 2012
北海茫月
北海茫月 2020-11-29 15:31

What is the difference between weak and strong property setter attributes in Objective-C?

@property(retain, [weak/strong]) __attribute__((NSObject)) CFDictio         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 16:31

    let take an example to elaborate more(above answer are already great), may this example helps little more

    let we have two class A and B

    //A.h
    
    #import 
    #import "B.h"
    
    @interface A : NSObject
    
    @property (nonatomic, strong) B *objB;
    
    @end
    
    @implementation A
    //
    
    @end
    
    //B.h
    
        #import 
        #import "A.h"
    
    
        @interface B : NSObject
    
        @property strong text(nonatomic, strong) A *objA;
    
        @end
    
        @implementation B
        //
    
        @end
    
        and in main
    
        #import "B.h"
        #import "A.h"
    
        {
        A *obja =[[A alloc]init];
        B *objb =[[B alloc]init];
        A.objB=objb;
        B.objA=obja;
       }
    

    the above code will generate a retain cycle because both are the strong type a-------->b--------->a

    so to avoid it you have to use week property of one of it so that it weekly refer to the object and not increase it reference count.

提交回复
热议问题