iOS-利用Runtime在項目里面快速找到ViewController

1.添加分類、利用Runtime方法交換實現(xiàn)實時監(jiān)控某個ViewController

//
//  UIViewController+Swizzling.m

#import "UIViewController+Swizzling.h"

#import @implementation UIViewController (Swizzling)

+ (void)load {

    //我們只有在開發(fā)的時候才需要查看哪個viewController將出現(xiàn)
    //所以在release模式下就沒必要進行方法的交換
#ifdef DEBUG

    //原本的viewWillAppear方法
    Method viewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:));

    //需要替換成 能夠輸出日志的viewWillAppear
    Method logViewWillAppear = class_getInstanceMethod(self, @selector(logViewWillAppear:));

    //兩方法進行交換
    method_exchangeImplementations(viewWillAppear, logViewWillAppear);

#endif

}

- (void)logViewWillAppear:(BOOL)animated {

    NSString *className = NSStringFromClass([self class]);

    //在這里,你可以進行過濾操作,指定哪些viewController需要打印,哪些不需要打印
    if ([className hasPrefix:@"UI"] == NO) {
        NSLog(@"%@ will appear",className);
    }

    //下面方法的調(diào)用,其實是調(diào)用viewWillAppear
    [self logViewWillAppear:animated];
}

@end

2.添加分類、利用Runtime快速定位到不能釋放的Viewcontroller

#import "UIViewController+Extension.h"
#import <objc/runtime.h>

@implementation UIViewController (Extension)

#pragma mark - swizzle
+ (void)load
{
    Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
    Method method2 = class_getInstanceMethod([self class], @selector(deallocSwizzle));
    method_exchangeImplementations(method1, method2);
}

- (void)deallocSwizzle
{
    NSLog(@"???%@???被銷毀了", self);
    
    [self deallocSwizzle];
}

3.給每個viewController添加屬性

@property (copy, nonatomic) NSString *method;

static char MethodKey;

- (void)setMethod:(NSString *)method
{
    objc_setAssociatedObject(self, &MethodKey, method, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)method
{
    return objc_getAssociatedObject(self, &MethodKey);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容