ios 消息转发初探

时间:2021-07-29 11:05:24

有时候服务器的接口文档上一个数据写的是string类型,这时候你就会直接把它赋值给一个label。

问题来了,有时候这个string的确是string,没有问题,有时候又是NSNumber,当然不管三七二十一,直接

NSString stringWithFormat:是对的,但是,每处都这样写,太累了,也就是对NSNumber length方法出现了崩溃,

简单使用消息转发处理就能搞定

+ (BOOL)resolveClassMethod:(SEL)sel
{ return NO;
} - (id)forwardingTargetForSelector:(SEL)aSelector { if (aSelector == @selector(length)) {
return [NSString stringWithFormat:@"%@", self];
}
if (aSelector == @selector(boundingRectWithSize:options:attributes:context:)) {
return [NSString stringWithFormat:@"%@", self];
}
if (aSelector == @selector(rangeOfCharacterFromSet:)) {
return [NSString stringWithFormat:@"%@", self];
}
if (aSelector == @selector(drawWithRect:options:attributes:context:)) {
return [NSString stringWithFormat:@"%@", self]; } return nil;
}