Apple开发_多类统一调用方法实现
1、首先定义一个协议,声明update_frame
方法:
@protocol GC_UpdateFrameProtocol <NSObject>
- (void)update_frame;
@end
2、让你的所有类都遵循这个协议:
@interface GC_Clock : UIView <GC_UpdateFrameProtocol>
// 实现已在原类中
@end
@interface GC_Button : UIButton <GC_UpdateFrameProtocol>
// 实现已在原类中
@end
@interface GC_Label : UIButton <GC_UpdateFrameProtocol>
// 实现已在原类中
@end
3、然后你就可以这样使用:
NSArray<id<GC_UpdateFrameProtocol>> *sub_array = @[clock, button, label];
for (id<GC_UpdateFrameProtocol> one_sub in sub_array) {
[one_sub update_frame];
}
4、这种方法的好处是:
-
- 不需要类型检查和强制转换
-
- 代码更简洁清晰
-
- 类型安全 - 编译器会检查数组中对象是否遵循协议
-
- 易于扩展 - 未来如果有新的类需要加入这个调用模式,只需要让它遵循协议即可
-
如果你不能修改这些类的声明(比如它们是在第三方库中),你可以使用类别(Category)来让它们遵循协议,但前提是这些类已经实现了
update_frame
方法。
🤖