其实质是对一个类的扩充,对类扩充的方法有两种:
(1)通过继承(经常用到)
(2)通过分类
一个已知类Name
其头文件Name.h
#import <Foundation/Foundation.h>
@interface Name : NSObject
@property(strong,nonatomic)NSString* nameStr;
-(Name *)init:(NSString*)nameString;
-(void)nameValue;
@end
其实现文件 Name.m
#import "Name.h"
@implementation Name
-(Name *)init:(NSString*)nameString
{
Name * name = [Name new];
name.nameStr = nameString;
return name;
}
-(void)nameValue
{
NSLog(@"----%@--",self.nameStr);
}
@end
再新建一个头文件Name+change.h用来声明其所要扩充的方法
源码:
#import "Name.h"
@interface Name(change)
-(void)addNameID:(NSString *)str;
@end
再新建一个实现文件Name+change.m用来实现自己扩充的方法
#import <Foundation/Foundation.h>
#import "Name+change.h"
#import "Name.h"
@implementation Name (change)
-(void)addNameID:(NSString *)str
{
NSLog(@"---%@--%@--",self.nameStr,str);
}
@end
其测试文件选择命令行
main.m
#import <Foundation/Foundation.h>
#import "Name+change.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Name * name1 = [[Name alloc] init:@"wangfei"];
[name1 nameValue];
[name1 addNameID:@"898989"];
}
return 0;
}
其测试结果:
2015-07-11 16:34:53.051 Category[1462:60100] ----wangfei--
2015-07-11 16:34:53.053 Category[1462:60100] ---wangfei--898989--
Program ended with exit code: 0