033*:strong和weak,(strong=retain+release)weak(self指针地址和weakSelf地址不一样、 weakSelf没有对引用计数+1)

问题

1:  weak表其实是一个哈希表,key是所指对象的指针,value是weak指针的地址数组。(value是数组的原因是:因为一个对象可能被多个弱引用指针指向)

Runtime维护了一张weak表,用来存储某个对象的所有的weak指针。

2:  当前self取地址 和 weakSelf取地址的值是不一样的

3:   weakSelf没有对内存进行+1操作

目录

1:ARC & MRC

2: strong & weak

3:强弱引用

4:NSProxy虚基类

5:weakSelf 与 self

预备

 

正文 

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表其实是一个哈希表,key是所指对象的指针,value是weak指针的地址数组。(value是数组的原因是:因为一个对象可能被多个弱引用指针指向)

Runtime维护了一张weak表,用来存储某个对象的所有的weak指针。

  • weak不处理(对象)的引用计数,而是使用一个哈希结构弱引用表进行信息保存
  • 对象本身的引用计数0时,调用dealloc函数,触发weak表的释放

  • 弱引用表存储细节
  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:

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

3. 强弱引用

  • NSTimer(计时器)切入点代码案例
- (void)createTimer {
    self.timer = [NSTimer timerWithTimeInterval:1 target:self 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。)

  • 一般来说,循环引用可以通过加入弱引用对象,打断循环:self -> timer -> 加入weakself-> self

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

  • 很不巧:

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

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

方法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

 

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 

虚基类代理模式使用非常方便使用场景也很。(注意proxy中是weak弱引用object

这样做的主要目的是将强引用的注意力转移成了消息转发。虚基类只负责消息转发,即使用NSProxy作为中间代理、中间者

这里有个疑问,定义的proxy对象,在dealloc释放时,还存在吗?

  • proxy对象会正常释放,因为vc正常释放了,所以可以释放其持有者,即timer和proxytimer的释放也打破了runLoop对proxy的强持有。完美的达到了两层释放,即 vc -×-> proxy <-×- runloop,解释如下:
    • vc释放,导致了proxy的释放

    • dealloc方法中,timer进行了释放,所以runloop强引用也释放了

这样做的主要目的是将强引用的注意力转移成了消息转发。虚基类只负责消息转发,即使用NSProxy作为中间代理、中间者

这里有个疑问,定义的proxy对象,在dealloc释放时,还存在吗?

  • proxy对象会正常释放,因为vc正常释放了,所以可以释放其持有者,即timer和proxytimer的释放也打破了runLoop对proxy的强持有。完美的达到了两层释放,即 vc -×-> proxy <-×- runloop,解释如下:
    • vc释放,导致了proxy的释放

    • dealloc方法中,timer进行了释放,所以runloop强引用也释放了

5:weakSelf 与 self

对于weakSelf和 self,主要有以下两个疑问

  • 1、weakSelf会对引用计数进行+1操作吗?

  • 2、weakSelf和 self的指针地址相同吗,是指向同一片内存吗?

  • 带着疑问,我们在weakSelf前后打印self的引用计数

NSLog(@"%ld",CFGetRetainCount((__bridge CFTypeRef)self));
__weak typeof(self) weakSelf = self;
NSLog(@"%ld",CFGetRetainCount((__bridge CFTypeRef)self));

 

因此可以得出一个结论:weakSelf没有对内存进行+1操作
  • 继续打印weakSelf 和 self对象,以及指针地址
po weakSelf
po self

po &weakSelf
po &self

结果如下 

从打印结果可以看出,当前self取地址 和 weakSelf取地址的值是不一样的。意味着有两个指针地址,指向的是同一片内存空间,即weakSelf 和 self 的内存地址是不一样,都指向同一片内存空间
  • 从上面打印可以看出,此时timer捕获的是<LGTimerViewController: 0x7f890741f5b0>,是一个对象,所以无法通过weakSelf来解决强持有。即引用链关系为:NSRunLoop -> timer -> weakSelf(<LGTimerViewController: 0x7f890741f5b0>)。所以RunLoop对整个 对象的空间有强持有,runloop没停,timer 和 weakSelf是无法释放的

  • 而我们在Block原理中提及的block的循环引用,与timer的是有区别的。通过block底层原理的方法__Block_object_assign可知,block捕获的是 对象的指针地址,即weakself 是 临时变量的指针地址,跟self没有关系,因为weakSelf是新的地址空间。所以此时的weakSelf相当于中间值。其引用关系链为self -> block -> weakSelf(临时变量的指针地址),可以通过地址拿到指针

所以在这里,我们需要区别下blocktimer循环引用的模型

  • timer模型self -> timer -> weakSelf -> self,当前的timer捕获的是B界面的内存,即vc对象的内存,即weakSelf表示的是vc对象

  • Block模型self -> block -> weakSelf -> self,当前的block捕获的是指针地址,即weakSelf表示的是指向self的临时变量的指针地址

注意

 

引用

 

posted on 2020-12-05 18:19  风zk  阅读(61)  评论(0编辑  收藏  举报

导航