標籤:
漢斯哈哈哈
地址:http://mp.weixin.qq.com/s?__biz=MjM5OTM0MzIwMQ==&mid=209435129&idx=5&sn=9ba490c4cf4808fe3735a93aac9d2bee&scene=5&srcid=z8msdWoQOugKSai2Gygg#rd
在開發項目中,會有這樣變態的需求:
思考:wocao!這變態的需求,要拒絕他嗎?
switch判斷唄,考慮所有跳轉的因素?這不得寫死我...
switch
() {
case
:
break
;
default
:
break
;
}
我是這麼個實現的(runtime是個好東西)
利 用runtime動態產生對象、屬性、方法這特性,我們可以先跟服務端商量好,定義跳轉規則,比如要跳轉到A控制器,需要傳屬性id、type,那麼服務 端返回字典給我,裡面有控制器名,兩個屬性名稱跟屬性值,用戶端就可以根據控制器名產生對象,再用kvc給對象賦值,這樣就搞定了 ---O(∩_∩)O哈哈哈
比如:根據推送規則跳轉對應介面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
{
// 類名
NSString *class =[NSString stringWithFormat:@
"%@"
, params[@
"class"
]];
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];
// 對該對象賦值屬性
NSDictionary * propertys = params[@
"property"
];
[propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
// 檢測這個對象是否存在該屬性
if
([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
// 利用kvc賦值
[instance setValue:obj forKey:key];
}
}];
// 擷取導航控制器
UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
// 跳轉到對應的控制器
[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
iOS 萬能跳轉介面方法 (runtime實用篇一)