美文网首页
Runtime-开发中常用的代码段

Runtime-开发中常用的代码段

作者: ISwiftUI | 来源:发表于2017-02-04 14:51 被阅读16次

1.获取成员属性或者成员变量

        // OC成员变量
        MyClass *myClass = [[MyClass alloc] init];
        unsigned int outCount = 0;
        Class cls = myClass.class;
        Ivar *ivars = class_copyIvarList(cls, &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            NSLog(@"instance variable's name: %s at index: %d", ivar_getName(ivar), i);
        }
        free(ivars);

        // OC成员变量
        Ivar *ivars = class_copyIvarList(cls, &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            NSLog(@"instance variable's name: %s at index: %d", ivar_getName(ivar), i);
        }

        free(ivars);
        // swift 利用运行时机制查看所有的属性名称
         var count : UInt32 = 0
         let ivars = class_copyIvarList(UITableViewRowAction.self, &count)!
         for i in 0..<count {
         let ivar = ivars[Int(i)]
         let name = ivar_getName(ivar)
             print(String(cString: name!))
         }
        free(ivars)

2.runtime中的‘黑魔法’swizzledSelector

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

@implementation UIViewController (JQCore)

+(void)load {
    NSString*className=NSStringFromClass(self.class);
    NSLog(@"classname%@",className);
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        Class class=[self class];
        
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(bb_viewWillAppear:);
        
        Method originalMethod=class_getInstanceMethod(class,originalSelector);
        Method swizzledMethod=class_getInstanceMethod(class,swizzledSelector);
        
        BOOL didAddMethod=
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if(didAddMethod){
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        }else{
            method_exchangeImplementations(originalMethod,swizzledMethod);
        }
    });
}

#pragma mark - Runtime

-(void)bb_viewWillAppear:(BOOL)animated{
    NSLog(@"viewWillAppear:%@",self);
    [self bb_viewWillAppear:animated];
}

@end

3.属性关联

// 设置关联对象

void objc_setAssociatedObject ( id object, const void *key, id value, objc_AssociationPolicy policy );   
// 获取关联对象

id objc_getAssociatedObject ( id object, const void *key ); 
//移除关联对象

void objc_removeAssociatedObjects ( id object ); 
import Foundation
import ObjectiveC
import UIKit

extension UIView {
    
    // 改进写法【推荐】
    
    struct RuntimeKey {
        static let jkKey = UnsafeRawPointer.init(bitPattern: "JKKey".hashValue)
        /// ...其他Key声明
    }
    
    var jkPro: String? {
        set {
            objc_setAssociatedObject(self, RuntimeKey.jkKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        
        get {
            return objc_getAssociatedObject(self, RuntimeKey.jkKey) as? String
        }
    }
}

eg:

@end#import "UIViewController+HUD.h"
#import "MBProgressHUD.h"
#import <objc/runtime.h>

static const void * httpReqHUDKey = &httpReqHUDKey;

@implementation UIViewController (HUD)
- (MBProgressHUD *)HUD{
    return objc_getAssociatedObject(self, httpReqHUDKey);
}
- (void)setHUD:(MBProgressHUD *)HUD{
    objc_setAssociatedObject(self, httpReqHUDKey, HUD, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)showHudInView:(UIView *)view hint:(NSString *)hint{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:view];
    HUD.labelText = hint;
    [view addSubview:HUD];
    [HUD show:YES];
    [self setHUD:HUD];
}
@end

相关文章

网友评论

      本文标题:Runtime-开发中常用的代码段

      本文链接:https://www.haomeiwen.com/subject/omgjittx.html