美文网首页iOS-开发iOS 底层原理
OC底层原理三十六:内存管理(strong & weak & 强

OC底层原理三十六:内存管理(strong & weak & 强

作者: markhetao | 来源:发表于2020-11-28 21:38 被阅读0次

    OC底层原理 学习大纲

    • 👉 上一节 ,详细介绍了TaggedPointerretainreleasedealloc。本节,我们将介绍:
    1. ARC & MRC
    2. strong & weak
    3. 强弱引用

    准备工作:


    1. ARC & MRC

    Objective-C提供了两种内存管理机制

    • MRCMannul Reference Counting 手动管理引用计数)
    • ARCAutomatic Reference Counting 自动管理引用计数)

    MRC(手动管理引用计数)

    1. 通过allocnewcopymutableCopy生成的对象,持有时,需要使用retainreleaseautoRelease管理引用计数
    • retain对象引用计数+1
    • release对象引用计数-1
    • autoRelease:自动对作用域内对象进行一次retainrelease操作。
    1. MRC模式下,必须遵守:谁创建谁释放谁引用谁管理

    ARC(自动管理引用计数)

    1. ARCWWDC2011上公布,iOS5系统引入的自动管理机制,是LLVMRuntime配合的结果,在编译期运行时都会进行内存管理
    2. ARC禁止手动调用retainreleaseretainCountdealloc,转而使用weakstrong属性关键字。
    • 现在都是直接使用ARC,由系统自动管理引用计数了。

    2. strong & weak

    • 关于strongweak,可以在objc4源码中进行探索。 现在将流程图总结记录一下:

    2.1 weak

    • weak不处理(对象)的引用计数,而是使用一个哈希结构弱引用表进行信息保存
    • 对象本身的引用计数0时,调用dealloc函数,触发weak表的释放
      weak流程.png
    • 弱引用表存储细节
    1. weak使用weakTable弱引用表进行存储信息,是sideTable散列表(哈希表)结构。
    2. 创建weak_entry_t,将referent引用计数加入到weak_entry_t的数组inline_referrers中。
    3. 支持weak_table扩容,把new_entry加入到weak_table

    2.2 strong

    • strong修饰,实际是新值retain旧值release:
      image.png

    总结:

    1. weak处理引用计数,使用弱引用表进行信息存储dealloc移除记录
    2. strong: 内部使用retainrelease进行引用计数管理

    3. 强弱引用

    • NSTimer(计时器)切入点代码案例
    - (void)createTimer {
        self.timer = [NSTimer timerWithTimeInterval:1 target:weakSelf selector:@selector(fireHome) userInfo:nil repeats:YES];
         [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    - (void)fireHome{
        num++;
        NSLog(@"hello word - %d",num);
    }
    - (void)dealloc{
        [self.timer invalidate];
        self.timer = nil;
        NSLog(@"%s",__func__);
    }
    

    NSTimer创建后,需要手动加入Runloop中才可以运行,但timer会使得当前控制器不走dealloc方法,导致timer控制器都无法释放。

    下面,我们就来解决2个问题:

    1. 为什么?(timer加入后,控制器无法释放)
    2. 如何解决?

    3.1 强持有

    拓展:

    • 无法释放,一般是循环引用导致(可参考 👉 循环引用)
      (注意: self作为参数传入,不会被【自动持有】,除非内部手动强引用self)
    • NSTimertimerWithTimeInterval:target:selector:userInfo:repeats:方法,就手动强引用self
      image.png
    • 一般来说,循环引用可以通过加入弱引用对象,打断循环:self -> timer -> 加入weakself -> self

    • 对,原理没错。但前提是: timer�仅被self持有,且timer仅拷贝weakself指针!

    • 很不巧:

    1. 当前timer除了被self持有,还被加入了[NSRunLoop currentRunLoop]
    2. 当前timer直接指向self内存空间,是对内存进行强持有,而不是简单的指针拷贝
      所以currentRunLoop没结束,timer不会释放self内存空间不会释放

    block捕获外界变量:捕捉的是指针地址timer捕捉的是对象本身(内存空间)

    3.2 解决方法

    方法1:didMoveToParentViewController手动打断循环
    - (void)didMoveToParentViewController:(UIViewController *)parent{
        // 无论push 进来 还是 pop 出去 正常跑
        // 就算继续push 到下一层 pop 回去还是继续
        if (parent == nil) {
           [self.timer invalidate];
            self.timer = nil;
            NSLog(@"timer 走了");
        }
    }
    
    方法2:不加入Runloop,使用官方闭包API
    - (void)createTimer{
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSLog(@"timer fire - %@",timer);
        }];
    }
    
    方法3:中介者模式(不使用self)
    • 既然timer强持有对象(内存空间),我们就给他一个中介者内存空间,让他碰不到self,我们再对中介者操作和释放
    • HTTimer.h文件:
    @interface HTTimer : NSObject
    
    + (instancetype)scheduledTimerWithTimeInterval:(NSTimeInterval)interval target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)repeats;
    
    - (void)invalidate;
    
    - (void)fire;
    
    @end
    
    • HTTimer.m文件:
    @interface HTTimer ()
    
    @property (nonatomic, strong) NSTimer * timer;
    @property (nonatomic, weak) id aTarget;
    @property (nonatomic, assign) SEL aSelector;
    @end
    
    @implementation HTTimer
    
    + (instancetype)scheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)repeats {
        
        HTTimer * timer = [HTTimer new];
        
        timer.aTarget = aTarget;
        
        timer.aSelector = aSelector;
        
        timer.timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:timer selector:@selector(run) userInfo:userInfo repeats:repeats];
        
        [[NSRunLoop currentRunLoop] addTimer:timer.timer forMode:NSRunLoopCommonModes];
        
        return timer;
    }
    
    - (void)run {
        //如果崩在这里,说明你没有在使用Timer的VC里面的deinit方法里调用invalidate方法
        if(![self.aTarget respondsToSelector:_aSelector]) return;
        
        // 消除警告
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
       [self.aTarget performSelector:self.aSelector];
        #pragma clang diagnostic pop
        
    }
    
    - (void)fire {
        [_timer fire];
    }
    
    - (void)invalidate {
        [_timer  invalidate];
        _timer = nil;
    }
    
    - (void)dealloc
    {
        // release环境下注释掉
        NSLog(@"计时器已销毁");
    }
    
    @end
    
    • 使用方法:
    @interface TimerViewController ()
    @property (nonatomic, strong) HTTimer * timer;
    @end
    
    @implementation TimerViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // 创建
         self.timer = [HTTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(fireHome) userInfo:nil repeats:YES];
    }
    
    - (void)fireHome{
        NSLog(@"hello word" ); // 调用
    }
    
    - (void)dealloc{
        // 释放
        [self.timer invalidate];
        NSLog(@"%s",__func__);
    }
    @end
    
    image.png
    方法4 NSProxy虚基类
    • NSObject同级,但内部什么都没有,但是可以持有对象,并将消息全部转发对象
      (ps: 我啥也没有,但我也是对象,我可以把你需求全部传递能办事对象)

    这就是代理模式timer持有代理代理weak弱引用持有self,再把所有消息转发self

    • HTProxy.h文件
    @interface HTProxy : NSProxy
    
    /// 麻烦把消息转发给`object`
    + (instancetype)proxyWithTransformObject:(id)object;
    
    @end
    
    • HTProxy.m文件
    #import "HTProxy.h"
    
    @interface HTProxy ()
    @property (nonatomic, weak) id object; // 弱引用object
    @end
    
    @implementation HTProxy
    
    /// 麻烦把消息转发给`object`
    + (instancetype)proxyWithTransformObject:(id)object {
        HTProxy * proxy = [HTProxy alloc];
        proxy.object = object;
        return proxy;
    }
    
    // 消息转发。 (所有消息,都转发给object去处理)
    - (id)forwardingTargetForSelector:(SEL)aSelector {
        return self.object;
    }
    
    
    // 消息转发 self.object(可以利用虚基类,进行数据收集)
    //- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    //
    //    if (self.object) {
    //    }else{
    //        NSLog(@"麻烦收集 stack111");
    //    }
    //    return [self.object methodSignatureForSelector:sel];
    //
    //}
    //
    //- (void)forwardInvocation:(NSInvocation *)invocation{
    //
    //    if (self.object) {
    //        [invocation invokeWithTarget:self.object];
    //    }else{
    //        NSLog(@"麻烦收集 stack");
    //    }
    //
    //}
    
    -(void)dealloc {
        NSLog(@"%s",__func__);
    }
    @end
    
    • 使用方法:
    @interface TimerViewController ()
    @property (nonatomic, strong) HTProxy * proxy;
    @property (nonatomic, strong) NSTimer * timer;
    @end
    
    @implementation TimerViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 创建虚基类代理
        self.proxy = [HTProxy proxyWithTransformObject: self];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self.proxy selector:@selector(fireHome) userInfo:nil repeats:YES];
    }
    
    - (void)fireHome{
        NSLog(@"hello word" ); // 调用
    }
    
    - (void)dealloc{
        // 释放
        [self.timer invalidate];
        NSLog(@"%s",__func__);
    }
    @end
    
    image.png
    • 虚基类代理模式使用非常方便使用场景也很。(注意proxy中是weak弱引用object

    • 下一节,介绍自动释放池runloop

    相关文章

      网友评论

        本文标题:OC底层原理三十六:内存管理(strong & weak & 强

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