美文网首页
iOS开发 - OC中常见属性修饰词的作用及用法

iOS开发 - OC中常见属性修饰词的作用及用法

作者: 俺不是大佬儿 | 来源:发表于2021-12-07 23:06 被阅读0次

    OC项目出现循环引用/强引用的解决方法

    iOS开发dealloc方法不调用的原因

    快下班的时候测试告诉我,你的这个提示弹框怎么总是叠加重复弹出?发出了灵魂拷问,让我也是心里一紧,只能加个班了……

    经过排查是通知(NSNotificationCenter)被重复监听导致的,只能说明一个问题注册的通知监听没有及时销毁,只能是- (void)dealloc方法未被调用

    dealloc不调用一般有以下三个原因:

    ① 使用NSTimer计时器没有invalidate掉,这里要注意,先[_timer invalidate];然后再_timer = nil;就OK了;
    ② 有循环引用强引用的地方造成的(block中出现循环引用);
    ③ 使用了delegate没有取消或者是未使用weak/assign修饰

    经排查是因为多人开发的项目导致的block中出现循环引用引起的,一般使用__weak typeof(self) weakSelf = self可以使用以下的宏定义更方便的去解决block的循环引用问题

    #define kWeakSelf(type)__weak typeof(type)weak##type = type;
    
    #define kWS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
    
    #define kStrongSelf(type)__strong typeof(type)type = weak##type;
    

    也可以使用:

    @weakify();
    @strongify();
    

    同样也要避免出现强引用问题,合理使用属性修饰符:

    关键字 ARC或MRC 修饰对象说明
    atomic both 原子,线程安全,效率低,多线程操作时才使用
    nonatomic both 非原子,线程不安全,效率高,经常使用
    retain mrc 修饰对象 ,强引用
    strong arc 修饰对象,强引用
    weak arc 修饰代理delegate,修饰对象弱引用
    assign both 修饰基本数据类型(int,float,boolean)
    copy both 修饰字符串,block等

    常见的修饰词使用举例:

    
    @property (assign, nonatomic) NSInteger status;
    @property (assign, nonatomic) BOOL  isSelected;
    @property (copy,    nonatomic) NSString *city;
    @property (strong, nonatomic) NSArray    *bannerAdDataArr;
    @property (copy,    nonatomic) void (^UMSHARE_RESULT_BLOCK)(id resultData,UMSocialPlatformType platformType,NSError * error);
    @property (weak,   nonatomic) id <LRSSheetCityPickerDelegate> delegate;
    
    

    \color{gray}{努力码字,只为遇见你😊!}

    相关文章

      网友评论

          本文标题:iOS开发 - OC中常见属性修饰词的作用及用法

          本文链接:https://www.haomeiwen.com/subject/tqqzxrtx.html