iOS Category的理解

2017-04-10  本文已影响50人  乡下秋草

1.什么是Category?

category是Objective-C 2.0之后添加的语言特性,别人口中的分类、类别其实都是指的category。category的主要作用是为已经存在的类添加方法。除此之外,apple还推荐了category的另外两个使用场景。
可以把类的实现分开在几个不同的文件里面。这样做有几个显而易见的好处:

2.特点

3.代码

Animal 类

#import <Foundation/Foundation.h>
@interface Animal : NSObject
- (void)logName;
@end


#import "Animal.h"
@implementation Animal
- (void)logName{
    NSLog(@"this is animal");
}
@end

Person

#import <Foundation/Foundation.h>
#import "Animal.h"
@interface Animal (Person)
- (void)getPersonName;
- (void)eat;
@end
#import "Animal+Person.h"

@implementation Animal (Person)

- (void)eat{
    
    NSLog(@"person eat");
}

- (void)getPersonName{
    
    NSLog(@"this is a person");
}
@end

Cat

#import <Foundation/Foundation.h>
#import "Animal.h"

@interface Animal (Cat)
- (void)getCatName;

- (void)eat;

- (void)logName;
@end
@implementation Animal (Cat)
- (void)eat{
    
    NSLog(@"cat eat");
}

- (void)getCatName{
    
    NSLog(@"this is a cat");
}

- (void)logName{
    NSLog(@"this is cat");
    
}

Demo

    Animal *a = [[Animal alloc]init];
    [a getCatName];
    [a getPersonName];
    [a logName];//证明优先实现分类中的方法
    [a eat];//根据编译的顺序,后边的会覆盖前边的

打印结果

2017-04-10 17:42:38.281 TestProject[5029:810107] this is a cat
2017-04-10 17:42:38.282 TestProject[5029:810107] this is a person
2017-04-10 17:42:38.282 TestProject[5029:810107] this is animal
2017-04-10 17:42:38.282 TestProject[5029:810107] this is cat
2017-04-10 17:42:38.282 TestProject[5029:810107] person eat

两个类别的编译顺序改变后,输入也将改变


F3DFE1DF-2A91-463E-9483-10A268E77C0C.png
上一篇下一篇

猜你喜欢

热点阅读