您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

iOS 萬能跳轉界面方法:用 runtime 把跳轉規則交給後端(實用篇)

編輯:iOS 開發基礎

作者:漢斯哈哈哈,授權本站轉載。

項目裡經常會遇到這類「變態」需求:

  • 推送:根據服務端下發的數據規則,跳轉到對應的控制器。

  • feeds 列表:不同類型的 cell 可能跳轉到不同控制器。產品經理的說法往往是——「我也還不確定會跳哪個界面,可能是這個也可能是那個,能不能做靈活點,按後台返回的規則任意跳轉?」

第一反應大概是:用 switch 一個個 case 列舉所有跳轉因素?那基本等於把邏輯寫死,後續每加一個入口都要改客戶端。

// 直覺但不可維護的寫法
switch () {
    case :
        break;
    default:
        break;
}

我的做法:把跳轉規則做成數據(runtime 是個好東西)

利用 runtime 動態生成對象、動態賦值的能力,我們可以先和服務端約定一份跳轉協議。比如要跳轉到 A 控制器需要傳 id 和 type,那麼服務端就返回一個字典:裡面包含控制器類名,以及屬性名與屬性值的映射。客戶端根據類名動態生成對象,再用 KVC 批量賦值,跳轉就完成了。

下面以「根據推送規則跳轉到 HSFeedsViewController」為例。

HSFeedsViewController.h:

@interface HSFeedsViewController : UIViewController

// 進入該界面需要傳的屬性,服務器據此拉取對應的頻道列表數據
/** 頻道 ID */
@property (nonatomic, copy) NSString *ID;
/** 頻道 type */
@property (nonatomic, copy) NSString *type;

@end

AppDelegate.m 中,先約定推送消息的規則:

// 這個規則需要事先與服務端溝通好:跳轉到哪個界面、需要哪些參數
NSDictionary *userInfo = @{
    @"class": @"HSFeedsViewController",
    @"property": @{
        @"ID":   @"123",
        @"type": @"12"
    }
};

接收推送消息:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self push:userInfo];
}

核心的跳轉方法:

- (void)push:(NSDictionary *)params {
    // 1. 取出類名
    NSString *class = [NSString stringWithFormat:@"%@", params[@"class"]];
    const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];

    // 2. 嘗試從字符串拿到已有的類
    Class newClass = objc_getClass(className);
    if (!newClass) {
        // 拿不到就動態創建一個並註冊
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        objc_registerClassPair(newClass);
    }

    // 3. 創建對象
    id instance = [[newClass alloc] init];

    // 4. 遍歷屬性字典,逐個賦值
    NSDictionary *propertys = params[@"property"];
    [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 先確認該屬性存在,避免 KVC 崩潰
        if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
            [instance setValue:obj forKey:key];
        }
    }];

    // 5. 找到當前選中的導航控制器
    UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
    UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];

    // 6. 跳轉
    [pushClassStance 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;
}

完整示例與源碼:https://github.com/HHuiHao/Universal-Jump-ViewController

這套思路的價值在於:新增一個跳轉入口時,客戶端不需要改代碼,只要雙方對齊字段約定即可,後續還可以擴展成支持 webview、tab 切換、返回堆棧等多種目標類型。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved