一胜卤、運(yùn)行時
所謂運(yùn)行時账月,就是說程序在運(yùn)行(或者在被執(zhí)行時)的狀態(tài)综膀,運(yùn)行時對于項(xiàng)目編程來說是一個必要重要的機(jī)制,能夠幫我們處理很多未知的情況局齿,比如說動態(tài)創(chuàng)建類剧劝、添加屬性、方法等抓歼。
二担平、運(yùn)用領(lǐng)域
- 在程序運(yùn)行時,動態(tài)創(chuàng)建一個類
- 在程序運(yùn)行時锭部,動態(tài)為某類添加屬性、方法面褐,修改屬性值拌禾、方法名稱
- 。展哭。湃窍。
三闻蛀、這里簡單說一下方法交換機(jī)制
比如說一個工程里面,你們會使用很多系統(tǒng)控件您市,比如說UIButton觉痛,假設(shè)有一個需求說要將所有的button的點(diǎn)擊標(biāo)題顏色改成其他的顏色,難道你要一個一個去修改茵休?估計(jì)你會想死的心都有薪棒,那怎么辦?方法交換機(jī)制可以幫到你,
原始代碼:
UIButton *runTimeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[runTimeButton setFrame:CGRectMake(100, 100, 150, 30)];
[runTimeButton setTitle:@"button" forState:UIControlStateNormal];
[runTimeButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
[runTimeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
[runTimeButton setBackgroundColor:[UIColor whiteColor]];
[runTimeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:runTimeButton];
只要新建一個UIButton的分類榕莺,實(shí)現(xiàn)類似下面的代碼就可以實(shí)現(xiàn)方法的交換俐芯,這樣你就可以在不改動原始代碼的情況下實(shí)現(xiàn)所有按鈕的標(biāo)題顏色
新建分類代碼:
+ (void)load {
Method setTitleColorMethod = class_getInstanceMethod(self, @selector(setTitleColor:forState:));
Method hyc_setTitleColorMethod = class_getInstanceMethod(self, @selector(hyc_setTitleColor:forState:));
method_exchangeImplementations(setTitleColorMethod, hyc_setTitleColorMethod);
}
- (void)hyc_setTitleColor:(UIColor *)color forState:(UIControlState)state {
[self hyc_setTitleColor:[UIColor yellowColor] forState:state];
if (state == UIControlStateHighlighted) {
[self hyc_setTitleColor:[UIColor redColor] forState:state];
}
}
看看效果:
runtime效果.gif