iOS点点滴滴iOS 开发每天分享优质文章

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

2018-05-16  本文已影响42人  东篱先生_
  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消息转发实现破除循环引用(https://www.jianshu.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对象需要手动内存释放
    
上一篇 下一篇

猜你喜欢

热点阅读