Runtime的使用二, 知道类名跳转界面, 并实现传值

也是项目中的问题...., 类不同, 但是每个类要传的数据都是相同的, 熟知本人的人都知道, 我是一个能躺着绝对不会坐着, 能靠着绝对不会站着. 所有我会写重复一样的代码么?? 当然不会的.

这个没经过一个上午加一个中午, 经过了, 一个小时从网上找的代码😂🤣........

#import "WJRuntime.h"

#import <objc/runtime.h>
@implementation WJRuntime

  //runtime跳转

  + (void)runtimePush:(NSString *)vcName dic:(NSDictionary *)dic nav:(UINavigationController *)nav {
//类名(对象名)

NSString *class = vcName;

const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
Class newClass = objc_getClass(className);
if (!newClass) {
    //创建一个类
    Class superClass = [NSObject class];
    newClass = objc_allocateClassPair(superClass, className, 0);
    //注册你创建的这个类
    objc_registerClassPair(newClass);
}
// 创建对象(写到这里已经可以进行随机页面跳转了)
id instance = [[newClass alloc] init];

//下面是传值--------------

[dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
        //kvc给属性赋值
        
        [instance setValue:obj forKey:key];
    }else {
        NSLog(@"不包含key=%@的属性",key);
    }
}];
nav.hidesBottomBarWhenPushed = YES;
[nav pushViewController:instance animated:YES];

  }
  /**
   *  检测对象是否存在该属性
   */
  + (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
  {
unsigned int outCount, i;

// 获取对象里的属性列表
objc_property_t * properties = class_copyPropertyList([instance
                                                       class], &outCount);

for (i = 0; i < outCount; i++) {
    objc_property_t property =properties[i];
    //  属性名转成字符串
    NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
    // 判断该属性是否存在
    if ([propertyName isEqualToString:verifyPropertyName]) {
        free(properties);
        return YES;
    }
}
free(properties);

return NO;
  }

  @end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 王成打卡 领导者的资质#8期#关爱组 皓庭(北京)科技有限公司 一、【知~勤学】《以奋斗者为本》无 二、【行~实践...
    王成皓庭新风阅读 141评论 0 0
  • 高效率慢生活践行第305天 2018.9. 19晨间检视 ❤对着镜子中SPA后的自己笑笑,化个妆,美丽的心情。 就...
    江竹心阅读 614评论 1 4