iOS经验总结

iOS 内存泄露以及解决方案

2019-12-26  本文已影响0人  Jackxu_q

泄漏原因

在目前主要以ARC进行内存管理的开发模式,导致内寸泄漏的根本原因是代码中存在循环引用,从而导致一些内存无法释放,这就会导致delloc方法无法被调用。主要原因大概有一下几种类型

  1. Block循环引用
    原因:这个可能就是经常容易犯的一个问题了,Block体内使用实例变量也会造成循环引用,使得拥有这个实例的对象不能释放。因为该block本来就是当前类的一部分,现在子部门又强引用self,导致循环引用无法释放
    解决方案:

方法一: 对Block内要使用的对象A使用__weak进行修饰,Block对对象A弱引用打破循环。
有三种常用形式:

方法二:对Block内要使用的对象A使用____block进行修饰,并在代码块内,使用完__block变量后将其设为nil,并且该block必须至少执行一次。


    __block XXController *blkSelf = self;
       self.blk = ^{
        NSLog(@"In Block : %@",blkSelf);
       };

注意上述代码仍存在内存泄露,因为:

在block代码块内,使用完使用完__block变量后将其设为nil,并且该block必须至少执行一次后,不存在内存泄露,因为此时:

第二种使用__block打破循环的方法,优点是:

缺点也明显:

方法三:将在Block内要使用到的对象(一般为self对象),以Block参数的形式传入,Block就不会捕获该对象,而将其作为参数使用,其生命周期系统的栈自动管理,不造成内存泄露。
即原来使用__weak的写法:

    self.blk = ^{
        __strong typeof(self) strongSelf = weakSelf;
        NSLog(@"Use Property:%@", strongSelf.name);
        //……
    };
    self.blk();

改为Block传参写法后:

self.blk = ^(UIViewController *vc) {
        NSLog(@"Use Property:%@", vc.name);
    };
self.blk(self);

优点:

  1. delagete循环引用

在委托问题上出现循环引用问题已经是老生常谈了,规避该问题的杀手锏也是简单到哭,一字诀:声明delegate时请用assign(MRC)或者weak(ARC),千万别手贱玩一下retain或者strong,毕竟这基本逃不掉循环引用了!

  1. NSTimer循环引用

平时我们使用NSTimer定时器可以说是非常的多了,但是我们可能会忽略一点,那就是NSTimer可能会导致循环引用。
声明:并非所有的NSTimer会导致循环引用,下面两种情况除外

1、非repeat类型的。非repeat类型的timer不会强引用target,因此不会出现循环引用。
2、block类型的,新api。iOS 10之后才支持,因此对于还要支持老版本的app来说,这个API暂时无法使用。当然,block内部的循环引用也要避免。

​ NSTimer创建方法有下面多种:(重点讲解下面这种)
NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector: (SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;

​ 使用这种方式创建的NSTimer,会默认加入到runloop中,同时会与调用对象之间产生循环引用指针。请看以下示例代码

@interface ViewController ()
@property (nonatomic, weak) NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(printstr) userInfo:nil repeats:YES];
}
- (void)printstr{
    NSLog(@"ViewController");
}
- (void)dealloc{

    NSLog(@"ViewController---dealloc");
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"%@",self.timer);
}
@end

虽然使用的是weak关键字进行修饰,但是还是页面关闭后,还是会调用printstr方法。不信你试试看。这其中原因请看scheduledTimerWithTimeInterval官方文档解释。

知道原因了吧,尽管你声明为weak,但是NSTimer内部还是会把target进行强引用。

解决方案:

用NSProxy代理对象解决

@interface TimerTargetProxy : NSProxy
@property (nullable, nonatomic, weak, readonly) id target;
+ (instancetype)proxyWithTarget:(id)target;
@end
#import "TimerTargetProxy.h"
@interface TimerTargetProxy ()
- (instancetype)initWithTarget:(id)target;
@end
@implementation TimerTargetProxy
- (instancetype)initWithTarget:(id)target{

    _target = target;
    return self;
}
+ (instancetype)proxyWithTarget:(id)target{
    return [[TimerTargetProxy alloc] initWithTarget:target];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    if ([self.target respondsToSelector:sel]) {
        return [self.target methodSignatureForSelector:sel];
    }
    return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
- (void)forwardInvocation:(NSInvocation *)invocation{
    SEL sel = [invocation selector];
    if ([self.target respondsToSelector:sel]) {
        [invocation invokeWithTarget:self.target];
    }else{
        [invocation setSelector:@selector(notfind)];
        [invocation invokeWithTarget:self];
    }
}
- (BOOL)respondsToSelector:(SEL)aSelector{
    return [self.target respondsToSelector:aSelector];
}
- (void)notfind{
    NSLog(@"notfind");
}
- (void)dealloc{
    NSLog(@"TimerTargetProxy---dealloc");
}
@end

调用的话 将Controller中的timer创建方法中的target换一下就行了,如下:

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:
[TimerTargetProxy proxyWithTarget:self] selector:@selector(printstr) 
userInfo:nil repeats:YES];
  1. 通知造成的内存泄漏

1.1、iOS9 以后,一般的通知,都不再需要手动移除观察者,系统会自动在dealloc 的时候调用 [[NSNotificationCenter defaultCenter]removeObserver:self]。iOS9 以前的需要手动进行移除。

原因是:iOS9 以前观察者注册时,通知中心并不会对观察者对象做 retain 操作,而是进行了 unsafe_unretained 引用,所以在观察者被回收的时候,如果不对通知进行手动移除,那么指针指向被回收的内存区域就会成为野指针,这时再发送通知,便会造成程序崩溃。

从 iOS9 开始通知中心会对观察者进行 weak 弱引用,这时即使不对通知进行手动移除,指针也会在观察者被回收后自动置空,这时再发送通知,向空指针发送消息是不会有问题的。

泄露检测工具

  1. Xcode自带工具Instrument

  2. MLeaksFinder

上一篇 下一篇

猜你喜欢

热点阅读