Category注意事项
本小节知识点:
- 【理解】分类的使用注意事项
- 【理解】分类的编译的顺序
1.分类的使用注意事项
@interface Person (NJ)
{
}
- (void)eat;
@end
@interface Person (NJ)
@property (nonatomic, assign) int age;
@end
@interface Person : NSObject
{
int _no;
}
@end
@implementation Person (NJ)
- (void)say
{
NSLog(@"%s", __func__);
NSLog(@"no = %i", _no);
}
@end
- 如果分类和原来类出现同名的方法, 优先调用分类中的方法, 原来类中的方法会被忽略
@implementation Person
- (void)sleep
{
NSLog(@"%s", __func__);
}
@end
@implementation Person (NJ)
- (void)sleep
{
NSLog(@"%s", __func__);
}
@end
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc] init];
[p sleep];
return 0;
}
输出结果:
-[Person(NJ) sleep]
2.分类的编译的顺序
- 多个分类中有同名方法,则执行最后编译的文件方法(注意开发中千万不要这么干)
@implementation Person
- (void)sleep
{
NSLog(@"%s", __func__);
}
@end
@implementation Person (NJ)
- (void)sleep
{
NSLog(@"%s", __func__);
}
@end
@implementation Person (MJ)
- (void)sleep
{
NSLog(@"%s", __func__);
}
@end
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc] init];
[p sleep];
return 0;
}
输出结果:
-[Person(MJ) sleep]
