Objective-C Runtime实战应用(一)

2017-06-29  本文已影响84人  CerasusLand

OC的运行时的总结:

OC运行时实践:

本文的重点在于运行时特性在实际开发中的应用:

1.动态添加类或实例

OBJC_EXPORT Class _Nullable
objc_allocateClassPair(Class _Nullable superclass, const char * _Nonnull name, 
                       size_t extraBytes) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);//创建一个类或者源类
OBJC_EXPORT void
objc_registerClassPair(Class _Nonnull cls) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);//向运行时系统注册通过objc_allocateClassPair创建的类
OBJC_EXPORT void
objc_disposeClassPair(Class _Nonnull cls) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);//销毁一个类和它关联的源类
#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface Person : NSObject

- (id)initWithFirstName: (NSString *)firstName lastName: (NSString *)lastName age: (NSUInteger)age;

@property (readonly) NSString *firstName;
@property (readonly) NSString *lastName;
@property (readonly) NSUInteger age;

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Class c = objc_allocateClassPair([NSObject class], "Person", 0);
        class_addIvar(c, "firstName", sizeof(id), log2(sizeof(id)), @encode(id));
        class_addIvar(c, "lastName", sizeof(id), log2(sizeof(id)), @encode(id));
        class_addIvar(c, "age", sizeof(NSUInteger), log2(sizeof(NSUInteger)), @encode(NSUInteger));
        
        Ivar firstNameIvar = class_getInstanceVariable(c, "firstName");
        Ivar lastNameIvar = class_getInstanceVariable(c, "lastName");
        ptrdiff_t ageOffset = ivar_getOffset(class_getInstanceVariable(c, "age"));
        
        IMP initIMP = imp_implementationWithBlock(^(id self, NSString *firstName, NSString *lastName, NSUInteger age) {
            object_setIvar(self, firstNameIvar, firstName);
            object_setIvar(self, lastNameIvar, lastName);
            
            char *agePtr = ((char *)(__bridge void *)self) + ageOffset;
            memcpy(agePtr, &age, sizeof(age));
            
            return self;
        });
        const char *initTypes = [[NSString stringWithFormat: @"%s%s%s%s%s%s", @encode(id), @encode(id), @encode(SEL), @encode(id), @encode(id), @encode(NSUInteger)] UTF8String];
        class_addMethod(c, @selector(initWithFirstName:lastName:age:), initIMP, initTypes);
        
        const char *objectGetterTypes = [[NSString stringWithFormat: @"%s%s%s", @encode(id), @encode(id), @encode(SEL)] UTF8String];
        
        IMP descriptionIMP = imp_implementationWithBlock(^(id self) {
            return [NSString stringWithFormat: @"<%@ %p: %@ %@ age %zd>", [self class], self, [self firstName], [self lastName], [self age]];
        });
        class_addMethod(c, @selector(description), descriptionIMP, objectGetterTypes);
        
        IMP firstNameIMP = imp_implementationWithBlock(^(id self) {
            return object_getIvar(self, firstNameIvar);
        });
        class_addMethod(c, @selector(firstName), firstNameIMP, objectGetterTypes);
        
        IMP lastNameIMP = imp_implementationWithBlock(^(id self) {
            return object_getIvar(self, lastNameIvar);
        });
        class_addMethod(c, @selector(lastName), lastNameIMP, objectGetterTypes);
        
        IMP ageIMP = imp_implementationWithBlock(^(id self) {
            char *agePtr = ((char *)(__bridge void *)self) + ageOffset;
            NSUInteger age;
            memcpy(&age, agePtr, sizeof(age));
            return age;
        });
        const char *ageTypes = [[NSString stringWithFormat: @"%s%s%s", @encode(NSUInteger), @encode(id), @encode(SEL)] UTF8String];
        class_addMethod(c, @selector(age), ageIMP, ageTypes);
        
        objc_registerClassPair(c);
        
        Class PersonC = NSClassFromString(@"Person");
        Person *alex = [[PersonC alloc] initWithFirstName: @"Alex" lastName: @"Trebek" age: 29];
        Person *sean = [[PersonC alloc] initWithFirstName: @"Sean" lastName: @"Connery" age: 42];
        
        NSArray *people = @[ alex, sean ];
        
        NSLog(@"%@", people);
    }
    return 0;
}

输出结果:

2016-06-12 10:44:22.778865+0800 AllocateClass[26079:26214721] (
    "<Person 0x100638aa0: Alex Trebek age 29>",
    "<Person 0x100638c20: Sean Connery age 42>"
)
Program ended with exit code: 0

2.关联对象的应用

我们可以再OC的分类里面添加方法,但是无法添加属性,这个时候Runtime就要发挥作用了。

runtime提供了三个函数来设置关联对象:
//设置关联对象 
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
//获取关联对象
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
//移除关联对象
OBJC_EXPORT void objc_removeAssociatedObjects(id object)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
    
//参数解释
id object               被关联的对象
const void *key             关联的key 必须唯一
id value                关联的对象
objc_AssociationPolicy policy       关联策略

//其中的关联策略就相当于我们的property中的copy assign之类的
OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically.
添加公共属性
#import "Dog.h"
@interface Dog (Husky)
@property (copy, nonatomic) NSString *liveArea;
@property (copy, nonatomic) NSString *weight;
@end

#import "Dog+Husky.h"
#import <objc/runtime.h>

char * const identifier = "dogTypeIdentifier";
@implementation Dog (Husky)
@dynamic weight;

- (NSString *)liveArea {
    id liveArea = objc_getAssociatedObject(self, identifier);
    return liveArea;
}

- (void)setLiveArea:(NSString *)liveArea {
    objc_setAssociatedObject(self, identifier, liveArea, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end

这样,我们可以直接用点语法,对属性直接操作。

@synthesize 和 @dynamic的区别:
这两者都是clang指定的编译器指令,@synthesize用来告诉编译器给我自动生成属性的getter\setter方法,@dynamic则告诉编译器属性的getter\setter方法没有在类中实现,而是在程序的其他地方实现(例如父类中或者是在运行时提供)。

添加私有成员变量

这里有一个好用的案例是给按钮添加事件回调,而不走target-action机制。

#import <UIKit/UIKit.h>

@interface UIButton (EventHandler)
//传入点击事件的回调
- (instancetype)initWithFrame:(CGRect)frame callback:(void (^)(UIButton *button))callbackBlock;

@end

#import "UIButton+EventHandler.h"
#import <objc/runtime.h>

const char *callback_identifier = "BUTTON_CALLBACK";
@interface UIButton()
@property (nonatomic, copy) void (^callbackBlock)(UIButton * button);
@end

@implementation UIButton (EventHandler)

- (void (^)(UIButton *))callbackBlock {
    return objc_getAssociatedObject(self, callback_identifier);
}

- (void)setCallbackBlock:(void (^)(UIButton *))callbackBlock {
    objc_setAssociatedObject(self, callback_identifier, callbackBlock, OBJC_ASSOCIATION_COPY);
}

- (instancetype)initWithFrame:(CGRect)frame callback:(void (^)(UIButton *))callbackBlock {
    if (self = [super initWithFrame:frame]) {
        self.callbackBlock = callbackBlock;
        [self addTarget:self action:@selector(didClickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)didClickAction:(UIButton *)button {
    __weak typeof(self) weakSelf = self;//注意这里应该用weak指针,避免循环引用
    weakSelf.callbackBlock(button);
}
@end

这样我们就可以在初始化button的时候就可以直接调用事件处理了。

self.btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50) callback:^(UIButton *button) {
        NSLog(@"点击事件");
    }];
ORM(Object Relational Mapping)对象模型关系映射

关联对象的另一个重要应用是解析json数据直接给模型赋值,一些第三方的json解析库(MJExtension等)就是运用了这个特性,下面是这种方式的一个简单实现:

- (instancetype)initWithDict:(NSDictionary *)dict {
    if (self = [self init]) {
        //(1)获取类的属性及属性对应的类型
        NSMutableArray *keys = [NSMutableArray array];
        NSMutableArray *attributes = [NSMutableArray array];
        /*
         * 例子
         * name = value3 attribute = T@"NSString",C,N,V_value3
         * name = value4 attribute = T^i,N,V_value4
         */
        unsigned int outCount;
        objc_property_t *properties = class_copyPropertyList([self class], &outCount);
        for (int i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            //通过property_getName函数获得属性的名字
            NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            [keys addObject:propertyName];
            //通过property_getAttributes函数可以获得属性的名字和@encode编码
            NSString *propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
            [attributes addObject:propertyAttribute];
        }
        //立即释放properties指向的内存
        free(properties);
        //(2)根据类型给属性赋值
        for (NSString *key in keys) {
            if ([dict valueForKey:key] == nil) continue;
            [self setValue:[dict valueForKey:key] forKey:key];
        }
    }
    return self;
}

同样的利用这个特性也能实现模型的本地化存储,用SQLite做本地化的时候,可以利用这个特性避免复杂的SQL的编写

var propertyNames: [String]? {
        get {
            var count: UInt32 = 0
            guard let properties = class_copyPropertyList(self.classForCoder, &count) else { return nil }
            var propertyNames: [String] = []
            for i in 0..<count {
                if let property: objc_property_t = properties[Int(i)] {
                    let name = String.init(cString: property_getName(property))
                    propertyNames += [name]
                }
            }
            return propertyNames
        }
    }
    
    var propertyAttributes: [String]? {
        get {
            var count: UInt32 = 0
            guard let properties = class_copyPropertyList(self.classForCoder, &count) else { return nil }
            var propertyAttributes: [String] = []
            for i in 0..<count {
                if let property: objc_property_t = properties[Int(i)] {
                    let attribute = String.init(cString: property_getAttributes(property))
                    propertyAttributes.append(attribute)
                }
            }
            return propertyAttributes
        }
    }

这是两段Swift3的代码,用于从属性中获取相应的类型和属性标识,虽然Swift 3.x版本对于运行时的支持甚少,但是只要我们的类继承自NSObject就可以用到Faundation框架中的runtime的特性了。

访问私有变量

我们知道,如果成员变量放在了.m文件中,就成了私有变量,但是我们依然可以通过Runtime获取,这时候,我们就需要知道成员变量的名称了,OC没有绝对的私有变量和方法,方法当然也可以这样获取出来.

Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);
上一篇 下一篇

猜你喜欢

热点阅读