在使用 OC 进行 iOS 开发的过程中,如一个类的方法不能满足我现在的要求,而又不想修改原类的结构,这是分类(category)就有很大的作用。而扩展可以看作是一种特殊的分类。
分类
// 使用分类方法时,导入分类头,分类跟原类写在同一个object-c file里才能获取相关方法
// NSString能直接调用其分类方法(相应分类都写在了NSString这个file里了)
// 分类中只能声明方法
@interface UIViewController (Test)
-(NSInteger)getStarTime;
@end
分类可以在不修改原来类的基础上,为一个类扩展方法,其最主要的用法就显而易见了。
扩展
扩展(extension)可以看作是分类的一个特例(匿名分类),定义在类文件中的没有名字的分类。
如果要想类的扩展可以在别的文件中使用,就要在类的.h文件中声明:
//// .h文件中
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIViewController()
-(void)testCategory;
@end
@implementation UIViewController
-(void)testCategory{
}
@end
@interface MyCategory : NSObject
@property(nonatomic,strong)UIViewController *viewContrller;
-(void)add:(id) value;
@end
//// .m文件中
#import "TestCategoryViewController.h"
#import "UIViewController+Test.h"
#import "MyCategory.h"
@interface TestCategoryViewController ()
@end
@implementation TestCategoryViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyCategory *nei=[[MyCategory alloc] init];
//因为在MyCategory.h文件中扩展了UIViewController,添加了MyCategory的方法所以可以在这个文件中使用
[nei.viewContrller testCategory];
[self getStarTime];
}