万能跳转界面

万能跳转界面,完美的解耦方案

目标:

1.我们不想import这个控制的名字,然后push到一个新的界面,

2.我们想通过一个字符串跳转到一个新的页面,

3.服务端下发一个页面的名字,我们可以正常跳转

收益:

1.实现灵活跳转

2.服务端控制

3.控制器解耦,业务解耦

实现方式:

/**
 *  跳转界面
 *  @param name 控制器名
 *  @param params 参数
 */
- (void)pushWithControllerName:(NSString *)name params:(NSDictionary *)params {
    const char *className = [name 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];
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([self checkPropertyWithInstance:instance propertyName:key]) {
            [instance setValue:obj forKey:key];
        }
    }];
    [self.navigationController pushViewController:instance animated:YES];
}

/**
 *  检测对象是否存在该属性
 */
- (BOOL)checkPropertyWithInstance:(id)instance propertyName:(NSString *)propertyName {
    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:propertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}

Demo链接: https://github.com/DuffYang/PerfectPush

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

推荐阅读更多精彩内容