-
👉 上一节 ,详细介绍了
TaggedPointer、retain、release、dealloc。本节,我们将介绍:
- ARC & MRC
- strong & weak
- 强弱引用
准备工作:
- 可编译的
objc4-781源码: https://www.jianshu.com/p/45dc31d91000
1. ARC & MRC
Objective-C提供了两种内存管理机制:
-
MRC(Mannul Reference Counting手动管理引用计数) -
ARC(Automatic Reference Counting自动管理引用计数)
MRC(手动管理引用计数)
- 通过
alloc、new、copy、mutableCopy生成的对象,持有时,需要使用retain、release、autoRelease管理引用计数
retain:对象的引用计数+1release:对象的引用计数-1autoRelease:自动对作用域内的对象进行一次retain和release操作。
MRC模式下,必须遵守:谁创建,谁释放,谁引用,谁管理
ARC(自动管理引用计数)
ARC在WWDC2011上公布,iOS5系统引入的自动管理机制,是LLVM和Runtime配合的结果,在编译期和运行时都会进行内存管理。ARC中禁止手动调用retain、release、retainCount、dealloc,转而使用weak、strong属性关键字。
- 现在都是直接使用
ARC,由系统自动管理引用计数了。
2. strong & weak
- 关于
strong和weak,可以在objc4源码中进行探索。 现在将流程图和总结记录一下:
2.1 weak
-
weak是不处理(对象)的引用计数,而是使用一个哈希结构的弱引用表进行信息的保存。 - 当
对象本身的引用计数为0时,调用dealloc函数,触发weak表的释放。
weak流程.png
弱引用表的存储细节
weak使用weakTable弱引用表进行存储信息,是sideTable散列表(哈希表)结构。- 创建
weak_entry_t,将referent引用计数加入到weak_entry_t的数组inline_referrers中。- 支持
weak_table扩容,把new_entry加入到weak_table中
2.2 strong
-
strong修饰,实际是新值的retain和旧值的release:
image.png
总结:
weak:不处理引用计数,使用弱引用表进行信息存储,dealloc时移除记录。strong:内部使用retain和release进行引用计数的管理。
- 关于
retain、release、dealloc的内容,请移步 👉 OC底层原理三十五:内存管理(TaggedPointer、引用计数)
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个问题:
- 为什么?(
timer加入后,控制器无法释放) - 如何解决?
3.1 强持有
拓展:
无法释放,一般是循环引用导致(可参考 👉 循环引用)
(注意:self作为参数传入,不会被【自动持有】,除非内部手动强引用了self。)
- 而
NSTimer的timerWithTimeInterval:target:selector:userInfo:repeats:方法,就手动强引用了self
image.png
一般来说,
循环引用可以通过加入弱引用对象,打断循环:self -> timer ->加入weakself-> self对,
原理没错。但前提是:timer�仅被self持有,且timer仅拷贝weakself指针!很不巧:
- 当前
timer除了被self持有,还被加入了[NSRunLoop currentRunLoop]中- 当前
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


