美文网首页
OC Runtime 常见的应用

OC Runtime 常见的应用

作者: 赵邦华 | 来源:发表于2020-11-03 21:55 被阅读0次

    OC Runtime特性让他具有一些新功能,可以应用在日常的工作中,下面介绍 Runtime 中常见的应用,可以简要总结为以下几点(都要用到<objc/runtime.h>库):

    1. 方法交换(Method Swizzle)
    2. 给分类(Category)添加属性
    3. 实现类的自动归档和自动解档
    4. 实现字典转模型

    方法交换(Method Swizzle)

    就是利用以下方法(来自<objc/runtime.h>库):

    // 获得某个类的实例对象方法
    Method class_getInstanceMethod(Class cls , SEL name)
      
    // 获得某个类的类方法
    Method class_getClassMethod(Class cls , SEL name)
      
    // 交换两个方法的实现
    void method_exchangeImplementations(Method m1 , Method m2)
    

    例子:

    @interface Person : NSObject
    - (void)speak;
    - (void)run;
    @end
      
    @implementation Person
    
    - (void)speak {
        NSLog(@"%s", __func__);
    }
    
    - (void)run {
        NSLog(@"%s", __func__);
    }
    
    @end
      
    Person *person = [[Person alloc] init];
    Method m1 = class_getInstanceMethod([Person class], @selector(speak));
    Method m2 = class_getInstanceMethod([Person class], @selector(run));
    method_exchangeImplementations(m1, m2);
    [person speak];  // -[Person run]
    [person run];  //  -[Person speak]
    

    给分类(Category)添加属性

    如果没有runtime,分类只能在运行时给类添加方法,不能添加实例变量,可以添加属性,但添加的属性没有gettersetter,只有扩展(extension)能再编译时给类添加方法、属性、实例变量(都是私有的),有了runtime,可以使用关联对象(Associated Object),为分类的属性添加gettersetter,具体为:

    // 为一个实例对象添加一个关联对象,用键key(字符串)来区分(可以是一个属性的名称),value为具体的关联对象的值,policy为存储策略(比如copy,strong等)
    void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
    
    // 通过实例对象和key,获取关联对象的值
    id objc_getAssociatedObject(id object, const void *key);
      
    // 删除实例对象的关联对象
    void objc_removeAssociatedObjects(id object);
    
    // objc_AssociationPolicy的定义如下
    typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
        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. */
    };
    

    例子:

    @interface Person (Name)
    @property(copy) NSString *personMame;
    @end
      
    @implementation Person (Name)
    
    -(void) setPersonMame:(NSString *)personMame {
        objc_setAssociatedObject(self, "personMame", personMame, OBJC_ASSOCIATION_COPY);
    }
    
    -(NSString *) personMame {
        return objc_getAssociatedObject(self, "personMame");
    }
    
    @end
    
    Person *person = [[Person alloc] init];
    person.personMame = @"Danny";
    NSLog(@"%@", person.personMame);  // Danny
    

    实现类的自动归档和自动解档

    要实现自动归档和解档,需要知道一个类的所有属性名称,在runtime中有如下实现方法:

    // 获得某个类的所有成员变量,返回在一个列表中
    Ivar *class_copyIvarList(Class cls , unsigned int *outCount)
      
    // 获得成员变量的名字
    const char *ivar_getName(Ivar v)
    

    例子:

    @interface Person : NSObject
    @property (copy) NSString *gender;
    @property (assign) int age;
    - (instancetype)initWithCoder:(NSCoder *)aDecoder;
    - (void)encodeWithCoder:(NSCoder *)aCoder;
    @end
      
    @implementation Person
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        // 获取所有成员变量
        if (self = [super init]) {
            unsigned int outCount = 0;
            Ivar *ivars = class_copyIvarList([self class], &outCount);
    
            for (int i = 0; i < outCount; i++) {
                Ivar ivar = ivars[i];
                // 将每个成员变量名转换为NSString对象类型
                NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
    
                // 根据变量名解档取值,无论是什么类型
                id value = [aDecoder decodeObjectForKey:key];
                // 取出的值再设置给属性
                [self setValue:value forKey:key];
                // 这两步就相当于以前的 self.age = [aDecoder decodeObjectForKey:@"_age"];
            }
            free(ivars);
        }
    
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)aCoder {
        unsigned int outCount = 0;
        Ivar *ivars = class_copyIvarList([self class], &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            // 将每个成员变量名转换为NSString对象类型
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
    
            // 通过成员变量名,取出成员变量的值
            id value = [self valueForKeyPath:key];
            // 再将值归档
            [aCoder encodeObject:value forKey:key];
        }
        free(ivars);
    }
    
    @end
      
    int main(int argc, const char *argv[])
    {
        @autoreleasepool {
            Person *person = [[Person alloc] init];
            person.age = 21;
            person.gender = @"male";
    
            // 定义归档文件路径
            NSString *pathPerson = [NSString stringWithFormat:@"%@/Documents/person", NSHomeDirectory()];
    
            // 调用归档函数
            [NSKeyedArchiver archiveRootObject:person toFile:pathPerson];
    
            //新建一个实例,来接受解归档的数据
            Person *personOut = [NSKeyedUnarchiver unarchiveObjectWithFile:pathPerson];
    
            NSLog(@"%d", personOut.age);  // 21
            NSLog(@"%@", personOut.gender);  // male
        }
        return 0;
    }
    

    实现字典转模型

    遍历模型的所有的属性,再去字典中根据属性名找对应值进行赋值

    例子:

    @interface Person : NSObject
    @property (copy) NSString *gender;
    @property (assign) int age;
    - (void)setDict:(NSDictionary *)dict;
    @end
      
    @implementation Person
    
    - (void)setDict:(NSDictionary *)dict {
        Class c = self.class;
        while (c && c != [NSObject class]) {
            unsigned int outCount = 0;
            Ivar *ivars = class_copyIvarList(c, &outCount);
            for (int i = 0; i < outCount; i++) {
                Ivar ivar = ivars[i];
                NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
    
                // 成员变量名转为属性名(去掉下划线 _ )
                key = [key substringFromIndex:1];
                
                // 取出字典的值
                id value = dict[key];
    
                // 如果模型属性数量大于字典键值对数理,模型属性会被赋值为nil而报错
                if (value == nil) continue;
    
                // 将字典中的值设置到模型上
                [self setValue:value forKeyPath:key];
            }
            free(ivars);
            c = [c superclass];
        }
    }
    
    @end
      
    int main(int argc, const char *argv[])
    {
        @autoreleasepool {
            Person *person = [[Person alloc] init];
            NSDictionary *dictionary = @{
                @"age": @21,
                @"gender": @"male"
            };
    
            [person setDict:dictionary];
    
            NSLog(@"%d", person.age);  // 21
            NSLog(@"%@", person.gender);  // male
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:OC Runtime 常见的应用

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