ARC下内存泄露的场景与解决方案

东篱先生_IP属地: 广东
字数 372阅读 625
  1. Block循环引用

    self持有Block,Block里又持有self,造成了一个引用环,最终导致self无法释放。

    // weakself弱引用不会让block持有self
    __weak typeof(self) weakself = self; 
     [self.label ly_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
         // strongself是为了防止weakself提前释放
         __strong typeof(self) strongself = weakself;
         [self dismissViewControllerAnimated:YES completion:nil];
     }];
    
  2. Delegate循环引用问题

    self持有delegate的拥有者,delegate拥有者通过strong持有self,造成循环引用。

    @property (nonatomic, weak) id delegate;
    
  3. NSTimer循环引用

    NSTimer会造成循环引用,timer会强引用target即self,一般self又会持有timer作为属性,这样就造成了循环引用。

     // 1.Block弱引用破除循环引用(https://www.cnblogs.com/H7N9/p/6540578.html)
     weak_self
     [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
         [weak_self dosomething];
     }];
    
     // 2.NSProxy消息转发实现破除循环引用(//www.greatytc.com/p/1ef002fcf314)
     // proxy子类weak的target,然后实现target的消息转发。
     // 初始化proxy子类
     self.proxy = [WBProxy alloc];
     // 作为当前控制器的代理
     self.proxy.obj = self;
     // target为代理
     self.timer = [NSTimer timerWithTimeInterval:1 target:self.proxy selector:@selector(timerEvent) userInfo:nil repeats:YES];
     [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    
  1. 非OC对象内存处理

    注意以creat,copy作为关键字的函数都是需要释放内存的,注意配对使用。比如:CGColorCreate<-->CGColorRelease

    CIImage *beginImage = [[CIImage alloc]initWithImage:[UIImage imageNamed:@"yourname.jpg"]];
    ...
    CGImageRelease(ref);//非OC对象需要手动内存释放
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
4人点赞
更多精彩内容,就在简书APP
"小礼物走一走,来简书关注我"
还没有人赞赏,支持一下
东篱先生_一只偏爱历史的程序猿。
总资产1共写了6101字获得23个赞共13个粉丝

推荐阅读更多精彩内容