返回
Objective-C 分类实现机制揭秘
IOS
2023-11-01 20:23:46
Objective-C 分类实现机制揭秘
Objective-C中的分类,在不修改原有类的情况下,为类添加额外的属性和方法。理解其内部实现机制,对于掌握Objective-C开发至关重要。
分类方法加入主类
分类中定义的方法,会被编译器生成一个名为_category_className
的特殊方法。该方法接收一个主类实例作为参数,并调用分类中定义的方法。例如,为Person
类添加一个分类,定义一个speak
方法:
@interface Person (Speak)
- (void)speak;
@end
@implementation Person (Speak)
- (void)speak {
NSLog(@"Hello!");
}
@end
编译器会生成如下代码:
@interface Person (Speak)
- (void)_category_speak:(Person *)person;
@end
@implementation Person (Speak)
- (void)_category_speak:(Person *)person {
[person speak];
}
@end
当调用分类中的speak
方法时,实际上调用的是_category_speak
方法,它再调用speak
方法。
方法覆盖
如果分类和主类中存在同名方法,则分类中的方法会覆盖主类中的方法。这是因为_category_speak
方法在调用时,直接调用了speak
方法,而不会再调用主类中的同名方法。
同名方法优先级
当多个分类中包含同名方法时,优先级为:
- 当前分类的方法
- 当前分类的父分类的方法
- 其他分类的方法
例如,为Person
类添加两个分类:
@interface Person (Speak)
- (void)speak;
@end
@implementation Person (Speak)
- (void)speak {
NSLog(@"Hello from Speak");
}
@end
@interface Person (Shout)
- (void)speak;
@end
@implementation Person (Shout)
- (void)speak {
NSLog(@"Hello from Shout");
}
@end
调用speak
方法时,优先调用Person (Shout)
中的speak
方法。
总结
Objective-C分类通过生成特殊方法实现,可以为现有类动态添加方法,并覆盖主类中的同名方法。理解分类的实现机制,有助于更深入掌握Objective-C开发。