RxSwift-deallocating,deallocated源码解析

deallocating,deallocated的使用

我们通常将deallocating序列结合takeUntil使用。达到当对象销毁时,序列会自动销毁的目的。

  let vc = LGDetialViewController()
        _ = vc.publicOB
            .takeUntil(vc.rx.deallocating)
        .subscribe(onNext: { (item) in
            print("订阅到 \(item)")
        })
        self.navigationController?.pushViewController(vc, animated: true)

本文对deallocating序列源码进行解析,了解RxSwift是如何监控一个对象的释放,并给订阅者发送消息的。

deallocating源码解析

想要精确知道一个对象的是否销毁,那就必须掌握对象dealloc方法是否执行。掌握dealloc方法是否执行,很容易就想到runtime的方法交换。RxSwift也是通过方法交换的方式实现的吗?我们进入源码一探究竟。

private let deallocSelector = NSSelectorFromString("dealloc")
   public var deallocating: Observable<()> {
        return self.synchronized {
            do {
                let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector)
                return proxy.messageSent.asObservable()
            }
            catch let e {
                return Observable.error(e)
            }
        }
    }

首先调用registerMessageInterceptor创建DeallocatingProxy对象. 参数是deallocSelector
dealloc在ARC下不允许直接@seleteror(dealloc),采用NSSelectorFromString("dealloc")方式解决。

  fileprivate func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T {
       ......
       var error: NSError?
        let targetImplementation = RX_ensure_observing(self.base, selector, &error)
        if targetImplementation == nil {
            throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown
        }

        subject.targetImplementation = targetImplementation!

        return subject
    }

通过方法名称,我们推测RX_ensure_observing应该是我们要分析的重要方法。

IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSErrorParam error) {
    __block IMP targetImplementation = nil;
    // Target is the second object that needs to be synchronized to TRY to make sure other swizzling framework
    // won't do something in parallel.
    // Even though this is too fine grained locking and more coarse grained locks should exist, this is just in case
    // someone calls this method directly without any external lock.
    @synchronized(target) {
        // The only other resource that all other swizzling libraries have in common without introducing external
        // dependencies is class object.
        //
        // It is polite to try to synchronize it in hope other unknown entities will also attempt to do so.
        // It's like trying to figure out how to communicate with aliens without actually communicating,
        // save for the fact that aliens are people, programmers, authors of swizzling libraries.
        @synchronized([target class]) {
            [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) {
                targetImplementation = [self ensurePrepared:target
                                               forObserving:selector
                                                      error:error];
            }];
        }
    }

    return targetImplementation;
}

进入方法-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error
经过查找,我们找到下面的关键代码

 if (![self swizzleDeallocating:deallocSwizzingTarget error:error]) {
            return nil;
        }

SWIZZLE_INFRASTRUCTURE_METHOD(
    void,
    swizzleDeallocating,
    ,
    deallocSelector,
    DEALLOCATING_BODY
)

这个方法用宏实现的。Swift下没有Load方法,使用宏定义预编译。使用宏可以获得更高的代码运行效率。
把这个宏还原成下列方法:

    - (BOOL)swizzleDeallocating:(Class __nonnull)class error:(NSErrorParam)error
        {
            SEL selector = deallocSelector;
        
        __unused SEL rxSelector = RX_selector(selector);
        IMP (^newImplementationGenerator)(void) = ^() {
        __block IMP thisIMP = nil;
        id newImplementation = ^void(__unsafe_unretained id self         DECLARE_ARGUMENTS(__VA_ARGS__)) {
        DEALLOCATING_BODY(__VA_ARGS__)
        
        struct objc_super superInfo = {
        .receiver = self,
        .super_class = class_getSuperclass(class)
        };
        
        void (*msgSend)(struct objc_super *, SEL DECLARE_ARGUMENTS(__VA_ARGS__))
        = (__typeof__(msgSend))objc_msgSendSuper;
        @try {
        return msgSend(&superInfo, selector ARGUMENTS(__VA_ARGS__));
        }
        @finally { NO_BODY(__VA_ARGS__) }
        };
        
        thisIMP = imp_implementationWithBlock(newImplementation);
        return thisIMP;
        };
        
        IMP (^replacementImplementationGenerator)(IMP) = ^(IMP originalImplementation) {
        __block void (*originalImplementationTyped)(__unsafe_unretained id, SEL DECLARE_ARGUMENTS(__VA_ARGS__) )
        = (__typeof__(originalImplementationTyped))(originalImplementation);
        
        __block IMP thisIMP = nil;
        id implementationReplacement = ^void(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__) ) {
        DEALLOCATING_BODY(__VA_ARGS__)
        @try {
        return originalImplementationTyped(self, selector ARGUMENTS(__VA_ARGS__));
        }
        @finally { NO_BODY(__VA_ARGS__) }
        };
        
        thisIMP = imp_implementationWithBlock(implementationReplacement);
        return thisIMP;
        };
        
        return [self ensureSwizzledSelector:selector
        ofClass:class
        newImplementationGenerator:newImplementationGenerator
        replacementImplementationGenerator:replacementImplementationGenerator
        error:error];
        }

进入-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector ofClass:(Class __nonnull)class newImplementationGenerator:(IMP(^)(void))newImplementationGenerator replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator error:(NSErrorParam)error方法

 IMP originalImplementation = method_getImplementation(existingMethodOnTargetClass);
  
    IMP implementationReplacementIMP = replacementImplementationGenerator(originalImplementation);

    IMP originalImplementationAfterChange = method_setImplementation(existingMethodOnTargetClass, implementationReplacementIMP);

代码中通过method_getImplementation获取dealloc当前的IMP originalImplementation
然后获取要替换的IMPimplementationReplacementIMP,然后使用method_setImplementationexistingMethodOnTargetClassMethod设置新的IMP。

到目前为止,我们已经验证deallocating序列是通过runtime的方式为交换delloc的实现,从而实现对对象释放的监控。
当对象调用dealloc方法,会进入replacementImplementationGenerator这个IMP

   IMP (^replacementImplementationGenerator)(IMP) = ^(IMP originalImplementation) {
        __block void (*originalImplementationTyped)(__unsafe_unretained id, SEL DECLARE_ARGUMENTS(__VA_ARGS__) )
        = (__typeof__(originalImplementationTyped))(originalImplementation);
        
        __block IMP thisIMP = nil;
        id implementationReplacement = ^void(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__) ) {
        DEALLOCATING_BODY(__VA_ARGS__)
        @try {
        return originalImplementationTyped(self, selector ARGUMENTS(__VA_ARGS__));
        }
        @finally { NO_BODY(__VA_ARGS__) }
        };
        
        thisIMP = imp_implementationWithBlock(implementationReplacement);
        return thisIMP;
        };

IMP中先执行DEALLOCATING_BODY(__VA_ARGS__),然后调用dealloc交换前的IMP.
DEALLOCATING_BODY也是宏实现的

#define DEALLOCATING_BODY(...)                                                        \
    id<RXDeallocatingObserver> observer = objc_getAssociatedObject(self, rxSelector); \
    if (observer != nil && observer.targetImplementation == thisIMP) {                \
        [observer deallocating];                                                      \
    }

代码中调用[observer deallocating],观察者是关联属性rxSelector,我们追溯到registerMessageInterceptor方法中, 知道序列的观察者是DeallocatingProxy
那么[observer deallocating]会来到DeallocatingProxy. deallocating()

@objc func deallocating() {
            self.messageSent.on(.next(()))
        }

DeallocatingProxy中保存ReplaySubject序列

  let messageSent = ReplaySubject<()>.create(bufferSize: 1)

DeallocatingProxy.deallocating()中对messageSent序列发送响应。
发送响应后,那么就会有订阅者来接收。由于deallocatingtakeUntil经常结合起来使用,那么分析一下takeUntil的源码,探索一下takeUntil内部是如何接收deallocating发送的响应非常有必要。想要了解takeUntil源码,请查阅RxSwift-TakeUntil源码分析

至此,deallocating的源码分析已经完成,deallocated的实现与deallocating基本一致,这里就不再赘述了。

总结:

1.创建序列messageSent,返回到外界。
2.通过method-swizzing监控对象的dealloc
3.当调用对象的dealloc,为messageSent发送响应.

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