分类
Category也称为分类、类目、类别等,Category可以在不修改原来类的基础上,为这个类补充一些方法
Category的格式
代码语言:javascript复制@interface Person (SS)
-(void)eat;
@end
Category的运用
- 在开发中,类的实现文件特别大,难于管理与维护,因此经常使用分类机制把类的实现代码划分成易于管理的小块,以便单独检视
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic,copy) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
@property (nonatomic,strong) NSArray *friendArray;
- (instancetype)initWithFristName:(NSString *)firstName withLastName:(NSString *)lastName;
- (void)addPerson:(Person *)person;
- (void)removePerson:(Person *)person;
- (BOOL)isFriendWithPerson:(Person *)person;
- (void)performDayWork;
- (void)takeVacationFromWork;
- (void)gotoTheCinema;
- (void)gotoSportGame;
@end
实现文件里,所有的方法都写在一个类,内容太多,所以我们可根据其不同功能分成多个分类
代码语言:javascript复制#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic,copy) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
@property (nonatomic,strong) NSArray *friends;
- (instancetype)initWithFristName:(NSString *)firstName withLastName:(NSString *)lastName;
@end
-------------------------
#import "Person.h"
@interface Person (Work)
- (void)performDayWork;
- (void)takeVacationFromWork;
@end
-------------------------
#import "Person.h"
@interface Person (Play)
- (void)gotoTheCinema;
- (void)gotoSportGame;
@end
-------------------------
#import "Person.h"
@interface Person (Friendship)
- (void)addPerson:(Person *)person;
- (void)removePerson:(Person *)person;
- (BOOL)isFriendWithPerson:(Person *)person;
@end
- 如果分类中有和原类中同名的方法,程序只会调用分类里的方法,如果多个分类中都有和原类中同名的方法,程序只会由编译器决定,编译器最后一个执行的方法来响应
@interface Person : NSObject
@property (nonatomic,strong) NSString *name;
-(void)sayName;
@end
@implementation Person
-(void)sayName{
NSLog(@"%@",self.name);
}
@end
------------------------------------
@interface Person (SS)
-(void)eat;
-(void)sayName;
@end
@implementation Person (SS)
-(void)eat{
NSLog(@"%s",__func__);
}
-(void)sayName{
NSLog(@"%s",__func__);
}
@end
-------------------------------------
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc]init];
p.name = @"ABC";
[p sayName];
[p eat];
}
参考
Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法