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

作者: 东篱先生_ | 来源:发表于2018-05-16 17:50 被阅读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对象需要手动内存释放
    

相关文章

  • 内存泄漏/管理

    ARC 下内存泄露的那些点performSelector延时调用导致的内存泄露iOS ARC下几种导致内存泄露的场...

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

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

  • 使用富文本OHAttributedLabel

    使用教程: 请在arc下使用,不要arc与mrc混用造成内存泄露! 源码地址 http://pan.baidu....

  • ARC下内存泄露总结

    1、Block的循环引用   在iOS4.2时,Apple推出ARC内存管理机制。这是一种编译期的内存管理方式,在...

  • ARC 下内存泄露的那些点

    ARC 下内存泄露的那些点 一、block 系列 在 ARC 下,当 block 获取到外部变量时,由于编译器无法...

  • 内存及性能优化

    1. 用ARC管理内存 ARC除了帮你避免内存泄露,ARC还可以帮你提高性能,它能保证释放掉不再需要的对象的内存。...

  • iOS 内存管理机制

    最近接手的一个 APP 项目有内存泄露问题, 由于用了 ARC 管理内存, 使得找出哪里内存泄露了变得更加困难, ...

  • 增强iOS应用程序性能方法

    1. 使用ARC进行内存管理 ARC除了能避免内存泄露外,还有助于程序性能的提升 2.在适当的情况下使用reuse...

  • ARC 下内存泄露的那些点

    block 解决循环引用 这样确实解决了循环引用,但考虑另一种情况。 这时,虽然循环引用解决了,但是异步打印却没有...

  • ARC下内存泄露的几种情况

    delegate设为strong造成的内存泄露(两个对象相互强引用) NSTimer 造成的内存泄露(两个对象相互...

网友评论

    本文标题:ARC下内存泄露的场景与解决方案

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