iOS Runtime 常用方法整理

Objective-C runtime是一个实现Objective-C语言的C库。对象可以用C语言中的结构体表示,而方法(methods)可以用C函数实现。事实上,他们 差不多也是这么干了,另外再加上了一些额外的特性。这些结构体和函数被runtime函数封装后,Objective-C程序员可以在程序运行时创建,检查,修改类,对象和它们的方法。
除了封装,Objective-C runtime库也负责找出方法的最终执行代码。当程序执行[object doSomething]时,不会直接找到方法并调用。相反,一条消息(message)会发送给对象(在这儿,我们通常叫它接收者)。runtime库会给次机会让对象根据消息决定该作出什么样的反应。
如下是部分runtime常用的方法整理:

动态创建类, 添加成员变量, 赋值并调用动态添加的方法

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 动态创建People类, 继承自NSObject类
    // 额外空间     未知,通常设置为 0
    Class People = objc_allocateClassPair([NSObject class], "Person", 0);
    
    // 以NSString*为例
    // 变量size sizeof(NSString)
    // 对齐     指针类型的为log2(sizeof(NSString*))
    // 类型     @encode(NSString*)
    // 添加_name 成员变量
    BOOL flag1 = class_addIvar([People class], "_name", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
    if (flag1) {
        NSLog(@"添加成员变量_name成功!");
    }
    // 添加_age 成员变量
    BOOL flag2 = class_addIvar([People class], "_age", sizeof(int), sizeof(int), @encode(int));
    if (flag2) {
        NSLog(@"添加成员变量_age成功!");
    }
    
    // 注册方法名为say:的方法
    SEL s = sel_registerName("say:");
    
    // 添加say:方法的实现
    // "v@:@"
    // v表示返回值为void, i表示返回值为int
    // @表示参数id(self)
    // :表示SEL(_cmd)
    // @表示id
    class_addMethod([People class], s, (IMP)sayFunction1, "v@:@");
    
    // 注册该类
    objc_registerClassPair([People class]);
    
    // 创建类的实例
    id peopleInstance = [[People alloc] init];
    
    // KVC 动态改变 对象peopleInstance 中的实例变量
    [peopleInstance setValue:@"老师" forKey:@"name"];
    //    Ivar nameVar = class_getInstanceVariable([People class], "_name");
    //    object_setIvar(peopleInstance, nameVar, @"老师");
    
    // 从类中获取成员变量Ivar
    Ivar ageIvar = class_getInstanceVariable([People class], "_age");
    // 为成员变量赋值
    object_setIvar(peopleInstance, ageIvar, @33);
    
    // 调用 peopleInstance 对象中的 s 方法选择器对应的方法
    //    objc_msgSend(peopleInstance, s, @"大家好!");
    ((void (*)(id, SEL, id))objc_msgSend)(peopleInstance, s, @"大家好!!!");
    
    // 当People类或者它的子类的实例还存在,则不能调用objc_disposeClassPair这个方法;因此这里要先销毁实例对象后才能销毁类;
    peopleInstance = nil;
    
    // 销毁类
    objc_disposeClassPair([People class]);
}

// 动态添加方法的实现
void sayFunction1(id self, SEL _cmd, id some) {
    Ivar ageIvar = class_getInstanceVariable([self class], "_age");
    NSString *age = object_getIvar(self, ageIvar);
    NSLog(@"%@岁的%@说: %@, %@", age,[self valueForKey:@"name"],some, NSStringFromSelector(_cmd));
}

获取属性, 成员变量 以及 方法

@implementation People

- (NSDictionary *)allProperties {
    unsigned int count = 0;
    
    // 获取类的所有属性, 如果没有属性count就为0
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    NSMutableDictionary *resultDict = [@{} mutableCopy];
    
    for (int i = 0; i < count; i++) {
        // 获取属性的名称和值
        const char *propertyName = property_getName(properties[i]);
        NSString *name = [NSString stringWithUTF8String:propertyName];
        id propertyValue = [self valueForKey:name];
        
        if (propertyValue) {
            resultDict[name] = propertyValue;
        } else {
            resultDict[name] = @"字典的key对应的value不能为nil哦!";
        }
    }
    
    // 这里properties是一个数组指针, 我们需要使用free函数来释放内存
    free(properties);
    
    return resultDict;
}

- (NSDictionary *)allIvars {
    unsigned int count = 0;
    NSMutableDictionary *resultDict = [@{} mutableCopy];
    
    // 获取类的所有成员变量ivar
    Ivar *ivars = class_copyIvarList([self class], &count);
    
    for (int i = 0; i < count; i++) {
        const char *ivarName = ivar_getName(ivars[i]);
        NSString *name = [NSString stringWithUTF8String:ivarName];
        id ivarValue = [self valueForKey:name];
        
        if (ivarValue) {
            resultDict[name] = ivarValue;
        } else {
            resultDict[name] = @"字典的key对应的value不能为nil哦~";
        }
    }
    
    free(ivars);
    
    return resultDict;
}

- (NSDictionary *)allMethods {
    unsigned int count = 0;
    NSMutableDictionary *resultDict = [@{} mutableCopy];
    
    Method *methods = class_copyMethodList([self class], &count);
    
    for (int i = 0; i < count; i++) {
        SEL methodSEL = method_getName(methods[i]);
        const char *methodName = sel_getName(methodSEL);
        NSString *name = [NSString stringWithUTF8String:methodName];
        
        unsigned int arguments = method_getNumberOfArguments(methods[i]);
        
        resultDict[name] = @(arguments - 2);
    }
    
    free(methods);
    
    return resultDict;
}

@end

给类添加 属性 及 回调block

// 在People的分类中进行

typedef void(^CodingCallBack)();

@interface People (Associated)

@property (strong, nonatomic) NSNumber *associatedBust; // 胸围
@property (copy, nonatomic) CodingCallBack associatedCallBack; // 写代码

@end


@implementation People (Associated)

- (NSNumber *)associatedBust {
    // 获取关联对象
    return objc_getAssociatedObject(self, @selector(associatedBust));
}

- (void)setAssociatedBust:(NSNumber *)associatedBust {
    // 设置关联对象
    objc_setAssociatedObject(self, @selector(associatedBust), associatedBust, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CodingCallBack)associatedCallBack {
    return objc_getAssociatedObject(self, @selector(associatedCallBack));
}

- (void)setAssociatedCallBack:(CodingCallBack)associatedCallBack {
    objc_setAssociatedObject(self, @selector(associatedCallBack), associatedCallBack, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

序列化 及 反序列化

@interface People2 : NSObject <NSCoding>

@property (nonatomic, copy) NSString *name; // 姓名
@property (nonatomic, strong) NSNumber *age; // 年龄
@property (nonatomic, copy) NSString *occupation; // 职业
@property (nonatomic, copy) NSString *nationality; // 国籍

@end

@implementation People2

// 反序列化数据
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count);
        
        for (int i = 0; i < count; i++) {
            const char *ivarName = ivar_getName(ivars[i]);
            NSString *name = [NSString stringWithUTF8String:ivarName];
            id value = [coder decodeObjectForKey:name];
            
            [self setValue:value forKey:name];
        }
        
        free(ivars);
    }
    return self;
}

// 序列化数据
- (void)encodeWithCoder:(NSCoder *)aCoder {
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self class], &count);
    
    for (int i = 0; i < count; i++) {
        const char *ivarName = ivar_getName(ivars[i]);
        NSString *name = [NSString stringWithUTF8String:ivarName];
        id ivarValue = [self valueForKey:name];
        
        [aCoder encodeObject:ivarValue forKey:name];
    }
    
    free(ivars);
}

@end

Json 及 model 互转

@interface People2 : NSObject

@property (nonatomic, copy) NSString *name; // 姓名
@property (nonatomic, strong) NSNumber *age; // 年龄
@property (nonatomic, copy) NSString *occupation; // 职业
@property (nonatomic, copy) NSString *nationality; // 国籍

// 生成model
- (instancetype)initWithDictionary:(NSDictionary *)dictionary;

// 转换成字典
- (NSDictionary *)covertToDictionary;

@end

@implementation People2

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
        for (NSString *key in dictionary.allKeys) {
            id value = dictionary[key];
            
            SEL setter = [self propertySetterByKey:key];
            if (setter) {
                //                objc_msgSend(self, setter, value);
                ((void(*)(id, SEL, id))objc_msgSend)(self, setter, value);
            }
        }
    }
    return self;
}

- (NSDictionary *)covertToDictionary {
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    
    if (count != 0) {
        NSMutableDictionary *resultDict = [@{} mutableCopy];
        
        for (int i = 0; i < count; i++) {
            const char *propertyName = property_getName(properties[i]);
            NSString *key = [NSString stringWithUTF8String:propertyName];
            
            SEL getter = [self propertyGetterByKey:key];
            if (getter) {
                id value = ((id (*)(id, SEL))objc_msgSend)(self, getter);
                if (value) {
                    resultDict[key] = value;
                } else {
                    resultDict[key] = @"字典的key对应的value不能为nil哦!";
                }
            }
        }
        
        free(properties);
        return resultDict;
    }
    
    free(properties);
    return nil;
}

// --------- private method --------------------------------------
- (SEL)propertySetterByKey:(NSString *)key {
    // set方法, 首字母大写
    NSString *propertySetterName = [NSString stringWithFormat:@"set%@:", key.capitalizedString];
    
    SEL setter = NSSelectorFromString(propertySetterName);
    if ([self respondsToSelector:setter]) {
        return setter;
    }
    return nil;
}

- (SEL)propertyGetterByKey:(NSString *)key {
    SEL getter = NSSelectorFromString(key);
    if ([self respondsToSelector:getter]) {
        return getter;
    }
    return nil;
}

@end

动态转换方法实现

// 添加了方法声明, 但是没有实现该方法
@interface People : NSObject

- (void)sing;

@end

@implementation People

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    // 我们没有给People类声明sing方法, 这里我们动态添加方法
    if ([NSStringFromSelector(sel) isEqualToString:@"sing"]) {
        class_addMethod([self class], sel, (IMP)otherSing, "v@:");
        return YES;
    }
    return [super resolveClassMethod:sel];
}

void otherSing(id self, SEL cmd) {
    NSLog(@"%@ 唱歌啦~~",((People *)self).name);
}

@end

修改方法调用对象

// Bird 类中并没有名字为 sing 的方法, 这时可以在Bird类中 将对象修改成People
@interface Bird : NSObject

@property (copy, nonatomic) NSString *name;

@end

@implementation Bird

// 第一步:我们不动态添加方法,返回NO,进入第二步;
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return NO;
}

// 第二部:我们不指定备选对象响应aSelector,进入第三步;
- (id)forwardingTargetForSelector:(SEL)aSelector {
    return nil;
}

// 第三步:返回方法选择器,然后进入第四部;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if ([NSStringFromSelector(aSelector) isEqualToString:@"sing"]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    return [super methodSignatureForSelector:aSelector];
}

// 第四部:这步我们修改调用对象
- (void)forwardInvocation:(NSInvocation *)anInvocation {
// 我们改变调用对象为People
    People *p = [[People alloc] init];
    p.name = @"t1";

    [p sing];
}

@end

修改调用的方法

@interface Bird : NSObject

@property (copy, nonatomic) NSString *name;

@end

@implementation Bird

// 第一步:我们不动态添加方法,返回NO,进入第二步;
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return NO;
}

// 第二部:我们不指定备选对象响应aSelector,进入第三步;
- (id)forwardingTargetForSelector:(SEL)aSelector {
    return nil;
}

// 第三步:返回方法选择器,然后进入第四部;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if ([NSStringFromSelector(aSelector) isEqualToString:@"sing"]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    return [super methodSignatureForSelector:aSelector];
}

// 第四部:这步我们修改调用方法
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    [anInvocation setSelector:@selector(dance)];
    // 还要指定是哪个对象的方法
    [anInvocation invokeWithTarget:self];
}

// 若forwardInvocation没有实现,则会调用此方法
- (void)doesNotRecognizeSelector:(SEL)aSelector {
    NSLog(@"消息无法处理: %@", NSStringFromSelector(aSelector));
}

- (void)dance {
    NSLog(@"跳舞!! come on!~");
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 创业本就是九十九死一生的事,创业失败是定数,创业成功是概率,不要因那些商业大佬的成功故事就扩大了创业成功的概率性,...
    迂墨李庆阅读 4,007评论 0 0
  • 2019/01/17 周四 晴 文 / 柒秒鱼忆 -01- 最后一次复查去医院,我犹豫了很久要不要找个人陪我一起,...
    柒秒鱼忆阅读 3,641评论 4 5
  • RANK15:菲尼克斯太阳 太阳队这个夏天明确了未来将以二年级生得分后卫德文布克作为建队核心,奈特也公开表示愿意接...
    岚亭叙阅读 5,488评论 1 0
  • 今天天气晴雨交替,风吹不断,犹如我的心情。时而满足的傻笑,时而又难过到无法自拔。上午被逗比团团治愈。下午被...
    妖娆的胖子阅读 3,184评论 3 0

友情链接更多精彩内容