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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,706评论 4 366
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,002评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,462评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,375评论 0 216
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,763评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,849评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,033评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,768评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,490评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,734评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,204评论 1 264
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,566评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,227评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,137评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,934评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,926评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,774评论 2 274