前面的篇幅中分析学习了iOS内存管理方面的知识点,包括
- 内存五大区、TiggedPointer、引用计数
- weak实现原理和销毁过程(散列表、引用计数表、弱引用表)
- block以及循环引用问题 本篇通过案例来分析学习强引用和弱引用相关的内容。
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。通过下图,可以清晰看出其内存关系:
-
弱引用
对上面的案例进行一些调整:
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方法:该方法在
libobjc.A.dylib库中,并且会调动objc_loadWeakRetained方法。下面查看其源码实现!在
objc_loadWeak方法中,传入的参数为location,即为弱引用的地址,其存储的指针指向堆区对象。见下图:查看
objc_loadWeakRetained的源码实现:id 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。见下图:why?我们再对案例做一些调整,多次获取弱引用所指向对象的引用计数,发现一直是2,不再变化!见下图:这是为什么呢?在一个弱引用指向一个对象时,会将该弱引用插入到对象所对应的弱引用表中,而在获取该弱引用的引用计数时,其底层源码实现是通过设置一个临时变量,临时变量通过
rootRetain方法,使引用计数变为2,weak实际操作的是临时变量。当rootRetain流程结束后,临时对象也被消耗,所以再次获取弱引用的引用计数依然是2。
2.Timer强引用问题
NSTimer和block在使用过程中都会存在循环引用的问题,但是NSTimer的情况更为特殊,因为NSTimer依赖于Runloop,会被Runloop强持有,导致NSTimer无法释放。block循环引用和解决方式参看:block以及循环引用问题;
下面通过一些案例来分析NSTimer的循环引用问题。
-
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为什么就可以释放了呢?在官方文档中有说明: -
中介者模式
使用一个第三方接收消息:
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"); } } @endNSProxy的基类可以被用来透明的转发消息,自定义的GFProxy通过weak修饰持有了viewController,NSTimer的target设置为GFProxy对象,所以NSTimer和viewController没有产生循环引用。但是NSTimer的消息会发送到GFProxy中,通过消息转发机制,转发给(weak)object去执行。这样即解决了循环引用问题,也保证了业务的交互。