Category
定义
封装是面向对象的一个特征,OC也不例外,如果封装了一个类,不想再改动它了,可是随着程序功能的增加,需要在那个类中增加一个小小的方法,这时我们就不必在那个类中做修改或者再定义一个子类,只需要在用到那个方法的时候随手添加一个该类的类别(category)即可。特性有:
- 在类目定义的方法,会成为原始类的一部分,与其他的调用没有区别;
- 通过给父类定义类目方法,其子类也会继承这些方法。如果子类添加类目方法,父类则不会拥有子类的类目方法。
Category
的创建
Category
的创建方式有两种,一种是在自定义类里创建,另一种是创建Category文件。
1、 在自定义类中创建
- 在
Person.h
中添加Creation类目和Life类目
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
@private
NSString *name;
int age;
}
@property (nonatomic,copy) NSString *name;
@property (nonatomic) int age;
- (void) test;
@end
// 创建Creation类目
@interface Person (Creation)
+ (id)personWithName:(NSString *)cName;
+ (id)personWithName:(NSString *)cName withAge:(int)cAge;
- (id)initWithName:(NSString *)cName;
- (id)initWithName:(NSString *)cName withAge:(int)cAge;
@end
// 创建Life类目
@interface Person(Life)
- (void) eat;
- (void) sleep;
- (void) play;
@end
- 创建
Person.m
#import "Person.h"
@implementation Person
@synthesize name,age;
- (void) test
{
NSLog(@"这是一个原始类的方法");
}
@end
// Creation类目的实现
@implementation Person(Creation)
+ (id)personWithName:(NSString *)cName
{
Person *person = [[Person alloc] init];
person.name = cName;
return person;
}
+ (id)personWithName:(NSString *)cName withAge:(int)cAge
{
Person *person = [[Person alloc] init];
person.name = cName;
person.age = cAge;
return person;
}
- (id)initWithName:(NSString *)cName
{
if(self = [super init]) {
self.name = cName;
}
return self;
}
- (id)initWithName:(NSString *)cName withAge:(int)cAge
{
if (self = [super init]) {
self.name = cName;
self.age = cAge;
}
return self;
}
@end
// LIfe类目的实现
@implementation Person(Life)
-(void) eat
{
NSLog(@"%@ is eating",self.name);
}
-(void) sleep
{
NSLog(@"%@ is sleep",self.name);
}
-(void) play
{
NSLog(@"%@ is play",self.name);
}
@end
- 在main方法中调用
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *tom = [Person personWithName:@"tom" withAge:18];
NSLog(@"名字是%@,年龄是:%d",tom.name,tom.age);
[tom test];
[tom eat];
[tom sleep];
[tom play];
}
return 0;
}
2、创建Category文件方式
创建Category文件方式可用于不可修改的系统类中,如NSArray、NSString等。
示例:完成给NSArray添加一个Convert功能的Category,实现对一串数字的前后位置转换。
- 创建
NSArray+Convert.h
文件
#import <Foundation/Foundation.h>
@interface NSArray (Convert)
+ (NSMutableArray *) arrayFromNumber:(int) number;
@end
- 创建
NSArray+Convert.m
文件
#import "NSArray+Convert.h"
@implementation NSArray (Convert)
+ (NSMutableArray *) arrayFromNumber:(int) number
{
NSMutableArray *array = [NSMutableArray array];
while (number) {
int last = number % 10;
number = number / 10;
[array addObject:[NSNumber numberWithInt:last]];
}
return array;
}
@end
- 在main方法中调用
#import <Foundation/Foundation.h>
// 引入 `NSArray+Convert.h`
#import "NSArray+Convert.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 测试NSArray的category
NSMutableArray *array = [NSArray arrayFromNumber:12345];
NSLog(@"数字转换:%@",array);
}
return 0;
}