前言
前面我们已经学习了几篇iOS内存相关的内容,分别如下:
本篇通过案例来分析学习强引用和弱引用相关的内容,请继续往下吧。
1. 引用计数探索
引入一个案例:
NSObject * objc = [NSObject alloc];
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)objc), objc, &objc);
NSObject * new_objc = objc;
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)objc), objc, &objc);
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)new_objc), new_objc, &new_objc);
创建了一个objc对象,打印其引用计数;新建一个new_objc引用,并赋值objc,再次打印他们的引用计数。输出结果如下:

输出结果和我们的设想是一样的,通过
alloc方法新建对象后,其isa指针extra_rc = 1。新建的引用new_objc,也指向这个对象,只是指针地址不同,引用计数变为2。通过下图,可以清晰看出其内存关系:
1.1 弱引用
对上面的案例进行一些调整,如下:
NSObject * objc = [NSObject alloc];
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)objc), objc, &objc);
__weak typeof(self) theWeak = objc;
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)objc), objc, &objc);
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)theWeak), theWeak, &theWeak);
objc赋值给弱引用theWeak,打印其引用计数应该是怎样的呢?请看以下的运行结果:

新建一个
oc对象,其引用计数为1,弱引用指向该对象后,引用计数不变依然为1,这是非常好理解的,问题就是弱引用对象theWeak的引用计数为什么为2呢?我们在以下的代码添加断点,如下:
NSLog(@"%ld ---- %@ ---- %p",CFGetRetainCount((__bridge CFTypeRef)theWeak), theWeak, &theWeak);
打开汇编断点,查看汇编发现其调用了objc_loadWeak方法如下:

进入
objc_loadWeak方法继续查看,如下:
该方法在
libobjc.A.dylib库中,并且会调动objc_loadWeakRetained方法,那么我们立即打开源码查看其流程。
在objc_loadWeak方法中,传入的参数为location,即为弱引用的地址,其存储的指针指向堆区对象。如下:

查看
objc_loadWeakRetained的源码实现,如下:
objc_loadWeakRetained(id *location)
{
id obj;
id result;
Class cls;
SideTable *table;
retry:
// fixme std::atomic this load
obj = *location;
if (obj->isTaggedPointerOrNil()) return obj;
table = &SideTables()[obj];
table->lock();
if (*location != obj) {
table->unlock();
goto retry;
}
result = obj;
cls = obj->ISA();
if (! cls->hasCustomRR()) {
// Fast case. We know +initialize is complete because
// default-RR can never be set before then.
ASSERT(cls->isInitialized());
if (! obj->rootTryRetain()) {
result = nil;
}
}
else {
// Slow case. We must check for +initialize and call it outside
// the lock if necessary in order to avoid deadlocks.
// Use lookUpImpOrForward so we can avoid the assert in
// class_getInstanceMethod, since we intentionally make this
// callout with the lock held.
if (cls->isInitialized() || _thisThreadIsInitializingClass(cls)) {
BOOL (*tryRetain)(id, SEL) = (BOOL(*)(id, SEL))
lookUpImpOrForwardTryCache(obj, @selector(retainWeakReference), cls);
if ((IMP)tryRetain == _objc_msgForward) {
result = nil;
}
else if (! (*tryRetain)(obj, @selector(retainWeakReference))) {
result = nil;
}
}
else {
table->unlock();
class_initialize(cls, obj);
goto retry;
}
}
table->unlock();
return result;
}
跟踪代码,发现对象会赋值给一个临时变量obj,obj的引用计数一直是1,最终obj会调用rootTryRetain方法。如下:

继续跟踪代码,最终会调用
rootRetain方法,方法也就是retain的底层实现,对引用计数进行操作,在这里弱引用指向对象的引用计数变为了2。如下:
这又是为什呢?对个
weak对象指向objc,其引用计数会不会一直叠加下去呢?请继续往下看:
发现弱引用对象的引用计数一直是2,并没有叠。着是为什么?
在一个弱引用指向一个对象时,会将该弱引用插入到对象所对应的
弱引用表中,而在获取该弱引用的引用计数时,其底层源码实现是通过设置一个临时变量,临时变量通过rootRetain方法,使引用计数变为2,weak实际操作的是临时变量。当rootRetain流程结束后,临时对象也被消耗,所以再次获取弱引用的引用计数依然是2。
2. Timer强引用问题
NSTimer和block在使用过程中都会存在循环引用的问题,但是NSTimer的情况更为特殊,因为NSTimer依赖于Runloop,会被Runloop强持有,导致NSTimer无法释放。block循环引用和解决方式参看:[iOS block底层原理分析(1)--循环引用]
2.1 案例分析
-
NSTimer使用block
引用以下的案例,并且运行结果如下:
案例分析
此种方式,NSTimer和ViewController都能够正常释放。 NSTimer强引用问题
通常我们采用下面的两种方式使用NSTimer,这种情况会出现Runloop对NSTimer进行强持有,导致其无法释放的问题。
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(fireHome) userInfo:nil repeats:YES];
self.timer = [NSTimer timerWithTimeInterval:1 target:weakSelf selector:@selector(fireHome) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
因为这里NSRunLoop -->NSTimer (强持有)-> weakSelf-> self,虽然传入的target是weakSelf,但是NSTimer对weakSelf进行了强持有,所以不会释放。在viewCtr的dealloc方法中调用[self.timer invalidate];也就没有效果,因为viewCtr的dealloc方法根本就不会执行。

在苹果的官方文档中也提到了这点,
NSTimer会对传入的target进行强持有。其实这个情况和block的一些案例是一样的,比如静态变量持有了weakSelf,此种情况也是会导致循环引用无法释放的问题:
// staticSelf_定义:
static ViewController *staticSelf_;
- (void)blockWeak_static {
__weak typeof(self) weakSelf = self;
staticSelf_ = weakSelf;
}
block内部使用__strong,强弱共舞,也是使用了强引用的方式使self延迟释放。
__weak typeof(self) weakSelf = self;
self.block = ^()
{
__strong __typeof(weakSelf)strongWeak = weakSelf;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@", strongWeak.name);
});
};
如果block捕获用__weak修饰的外部变量,其内部的变量也是用__weak修饰,下图为block捕获弱引用后,clang得出的结果:

带着疑问,NSTimer的循环引用问题应该怎么解决呢?请继续往下。
-
手动移除强引用
因为dealloc无法执行,所以将[self.timer invalidate];写在dealloc中也就没有什么效果。我们可以将该方法放在viewWillDisappear或者didMoveToParentViewController方法中,手动移除强引用。
手动移除强引用
这种方式需要根据业务的需求进行调整,有时候也并不能完全满足需要,不够灵活。调用invalidate为什么就可以释放了呢?在官方文档中有说明:
invalidate官方说明 -
中介者模式
使用一个第三方接收消息:
static int num = 0; // 静态
self.target = [[NSObject alloc] init];
class_addMethod([NSObject class], @selector(fireHome), (IMP)fireHomeObjc, "v@:");
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self.target selector:@selector(fireHome) userInfo:nil repeats:YES];
查看运行结果,如下:

通过定义的对象来接收消息。上面的运行结果发现,成功避免的
NSTimer对self的强持有问题,ViewController能够正常释放,并能够达到业务需求。但是这个方式也有其缺点,就是无法使用self里面的方法,业务上很难实现交互。
-
自定义
NSTimer
代码实现如下:
#import <Foundation/Foundation.h>
@interface LGTimerWapper : NSObject
- (instancetype)lg_initWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
- (void)lg_invalidate;
@end
#import "LGTimerWapper.h"
#import <objc/message.h>
@interface LGTimerWapper()
@property (nonatomic, weak) id target;
@property (nonatomic, assign) SEL aSelector;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation LGTimerWapper
// 中介者 vc dealloc
- (instancetype)lg_initWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo{
if (self == [super init]) {
self.target = aTarget; // vc
self.aSelector = aSelector; // 方法 -- vc 释放
if ([self.target respondsToSelector:self.aSelector]) {
Method method = class_getInstanceMethod([self.target class], aSelector);
const char *type = method_getTypeEncoding(method);
class_addMethod([self class], aSelector, (IMP)fireHomeWapper, type);
self.timer = [NSTimer scheduledTimerWithTimeInterval:ti target:self selector:aSelector userInfo:userInfo repeats:yesOrNo];
}
}
return self;
}
// 一直跑 runloop
void fireHomeWapper(LGTimerWapper *warpper){
if (warpper.target) { // vc - dealloc
void (*gf_msgSend)(void *,SEL, id) = (void *)objc_msgSend;
gf_msgSend((__bridge void *)(warpper.target), warpper.aSelector,warpper.timer);
}else{ // warpper.target
[warpper.timer invalidate];
warpper.timer = nil;
}
}
- (void)lg_invalidate{
[self.timer invalidate];
self.timer = nil;
}
- (void)dealloc{
NSLog(@"%s",__func__);
}
@end
自定义的LGTimerWapper中,使用了runtime和中介者的思路。
首先,因为
NSTimer和ViewController会产生循环应用,所以这里LGTimerWapper内部的NSTimer不再持有viewController,而是持有LGTimerWapper自己并且
self.target修饰为weak,当viewController被释放时,target也会被释放同时为了保证业务交互,采用
runtime特性,向LGTimerWapper中添加了与viewController一样的方法,在NSTimer调用对应的方法时,通过objc_msgSend向viewController发送一条消息,让viewController去完成相关的业务操作当
viewController释放时,target也会被置空,则直接调用invalidate方法完成NSTimer的释放。-
proxy虚基类
虚基类的声明见下图:
虚基类的声明
该类的主要功能是来接收消息!使用方法如下:
// 使用
self.proxy = [GFProxy proxyWithTransformObject:self];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self.proxy selector:@selector(fireHome) userInfo:nil repeats:YES];
// 自定义虚基类实现
@interface GFProxy : NSProxy
+ (instancetype)proxyWithTransformObject:(id)object;
@end
@interface GFProxy()
@property (nonatomic, weak) id object;
@end
@implementation GFProxy
+ (instancetype)proxyWithTransformObject:(id)object{
LGProxy *proxy = [LGProxy alloc];
proxy.object = object;
return proxy;
}
// 快速消息转发
//-(id)forwardingTargetForSelector:(SEL)aSelector {
// return self.object;
//}
// 慢速消息转发 - sel - imp -
- (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");
}
}
@end
NSProxy的基类可以被用来透明的转发消息,自定义的GFProxy通过weak修饰持有了viewController,NSTimer的target设置为GFProxy对象,所以NSTimer和viewController没有产生循环引用。但是NSTimer的消息会发送到GFProxy中,通过消息转发机制,转发给(weak)object去执行。这样即解决了循环引用问题,也保证了业务的交互。



