iOS动态调用Get Set方法,其实就是动态调用iOS的方法罢了,这一方面的很多文章,自己去拜读下吧!
1.http://my.oschina.net/ioslighter/blog/393902
2.http://www.cocoachina.com/ios/20100517/1465.html
3.http://blog.csdn.net/majiakun1/article/details/46424925
在实际应用上,当我们要处理类似这样的遍历:
[_existRedPointArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
if (obj && [obj isKindOfClass:[NSString class]]) {
if ([obj isEqualToString:@"userCenterBtn"]) {
[_userCenterBtn.badgeView setBadgeDisplay:YES];
}else if ([obj isEqualToString:@"presentCenterBtn"]){
[_presentCenterBtn.badgeView setBadgeDisplay:YES];
}else if ([obj isEqualToString:@"bbsCenterBtn"]){
[_bbsCenterBtn.badgeView setBadgeDisplay:YES];
}else if ([obj isEqualToString:@"strategyCenterBtn"]){
[_strategyCenterBtn.badgeView setBadgeDisplay:YES];
}else if ([obj isEqualToString:@"helpCenterBtn"]){
[_helpCenterBtn.badgeView setBadgeDisplay:YES];
}
}
}];
如果是几个还好,一个个判断,如果服务器的json一下子返回一大堆,难道一个个来判断,这时候我们可以用动态调用的方式:
[_existRedPointArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
NSString *obj = @"userCenterBtn";
SEL btnSel = NSSelectorFromString(obj);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
UIButton *button = [self performSelector:btnSel];
#pragma clang diagnostic pop
[button.badgeView setBadgeDisplay:YES];
}];
同理,如果要调用set方法:
NSString *setStr = [NSString capitalizedForFirst:key];
SEL setBtnSel = NSSelectorFromString([NSString stringWithFormat:@"set%@Btn:", setStr]);
if ([self respondsToSelector:setBtnSel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:setBtnSel withObject:button];
#pragma clang diagnostic pop
其实说白了,就是将类和对象字符化,用字符调用的方式!!