万能跳转界面

2018-09-12  本文已影响0人  韩大锤

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

目标:

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

上一篇 下一篇

猜你喜欢

热点阅读