iOS基础学习

Objective-C基础学习之Category基本概念和注意事

2017-10-11  本文已影响19人  WenJim

1.什么是Category

2.Category的格式

@interface ClassName (CategoryName)
NewMethod; //在类别中添加方法
//不允许在类别中添加变量
@end
@implementation ClassName(CategoryName)

NewMethod
... ...
@end
iOS中也选择这个创建Category.png

3.分类的使用注意事项

@interface Person (WJ)
{
//    错误写法
//    int _age;
}
- (void)eat;
@end
@interface Person (WJ)
// 只会生成getter/setter方法的声明, 不会生成实现和私有成员变量
@property (nonatomic, assign) int age;
@end
分类可以访问原来类中的成员变量
@interface Person : NSObject
{
    int _no;
}
@end

@implementation Person (WJ)
- (void)say
{
    NSLog(@"%s", __func__);
    // 可以访问原有类中得成员变量
    NSLog(@"no = %i", _no);
}
@end
@implementation Person

- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

@implementation Person (WJ)
- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

int main(int argc, const char * argv[]) {
    Person *p = [[Person alloc] init];
    [p sleep];
    return 0;
}

输出结果:
-[Person(WJ) sleep]

4.分类的编译的顺序

@implementation Person

- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

@implementation Person (WJ)
- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

@implementation Person (CWJ)
- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

int main(int argc, const char * argv[]) {
    Person *p = [[Person alloc] init];
    [p sleep];
    return 0;
}

输出结果:
-[Person(CWJ) sleep]
Category编译顺序.png
上一篇 下一篇

猜你喜欢

热点阅读