前面的篇幅中分析学习了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"); } } @end
NSProxy
的基类可以被用来透明的转发消息,自定义的GFProxy
通过weak
修饰持有了viewController
,NSTimer
的target
设置为GFProxy
对象,所以NSTimer
和viewController
没有产生循环引用。但是NSTimer
的消息会发送到GFProxy
中,通过消息转发机制,转发给(weak)object
去执行。这样即解决了循环引用问题,也保证了业务的交互。