分类和扩展的必要性:
Object-c语言的动态性,不但体现在继承和重写上,还有一个非常强大的功能就是分类和扩展,比如一个类的方法不能满足我现在的要求,而且我还不想修改原类的结构,这是分类就有很大的作用,有时我们想修改原来也不可能,不如系统提供的类,像NSString,UIViewController等,我们要是想给他们新的功能方法,只能用扩展。
其实一个APP设计开始好多系统的基础类NSString,UIViewController,NSArray,NSDictionary,NSTabView等各种view可能 不会满足公司的特殊需求,所以我们在大架构的初始阶段可以,扩展系统的相应的类,添加我们想要的方法,作为我们公司定制后的系统的类,然后作为基类使用,会为今后的开发省去好多的繁琐的工作。
分类和扩展的概念:
@interface UIViewController (QXViewController)
//分类中只能声明方法 需要使用这个多加的方法只要在使用的地方导入#import "UIViewController+QXViewController.h"就可以了
//如果只导入UIViewController.h是不行的,是不会看到分类中新加的方法的,因为分类,跟原类 没有写在同一个object-c file里
//NSString就可以,因为系统把它所有的分类都写在了NSString这个file里了
-(NSInteger)getStarTime;
@end
建立分类的步骤:
分类中只能添加“方法”,不能增加成员变量。
分类中可以访问原来类中的成员变量,但是只能访问@protect和@public形式的变量。如果想要访问本类中的私有变量,分类和子类一样,只能通过方法来访问。如果一定要在分类中添加成员变量,可以通过getter,setter手段进行添加
扩展extension是分类的特例,就是匿名的分类:
@interface NeiBuCategory()
//扩展其实就是分类的一个特例,就是没有名字,匿名的分类就是扩展,由于是在.m文件中声明的分类,所以是优化的,外面是看不到remove:这个方法的
-(void)remove:(id)value;
@end
@implementation NeiBuCategory
-(instancetype)init{
if(self=[super init]){
self.viewContrller=[[UIViewController alloc] init];
return self;
}else{
return nil;
}
}
-(void)add:(id)value{
[_viewContrller testCategory];
}
-(void)remove:(id)value{
}
@end
如果要想扩展可以在别的文件中使用就要在.h文件中声明:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIViewController()//匿名分类就是扩展了UIViewController,而且是在NeiBuCategory.h中声明的,所以外部的文件都可以使用testCategory方法
//只要导入NeiBuCategory.h就行
-(void)testCategory;
@end
@implementation UIViewController
-(void)testCategory{
}
@end
@interface NeiBuCategory : NSObject
@property(nonatomic,strong)UIViewController *viewContrller;
-(void)add:(id) value;
@end
使用NeiBuCategory.h内部声明扩展的UIViewController:
#import "TestCategoryViewController.h"
#import "UIViewController+QXViewController.h"
#import "NeiBuCategory.h"
@interface TestCategoryViewController ()
@end
@implementation TestCategoryViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NeiBuCategory *nei=[[NeiBuCategory alloc] init];
[nei.viewContrller testCategory];//因为在NeiBuCategory.h文件中扩展了UIViewController,添加了testCategory的方法所以可以在这个文件中使用
//如果是在 NeiBuCategory.m文件扩展UIViewController,添加了testCategory的方法在这里就不能使用,因为是私有的只能在NeiBuCategory.m中使用
[self getStarTime];//导入#import "UIViewController+QXViewController.h"才可以用,只是导入UIViewController.h不行,getStartTime的扩展的//UIViewController不是在系统的UIViewController文件里声明的,而是一个新的文件:
/**
#import <UIKit/UIKit.h>
@interface UIViewController (QXViewController)
//分类中只能声明方法 需要使用这个多加的方法只要在使用的地方导入#import "UIViewController+QXViewController.h"就可以了
//如果只导入UIViewController.h是不行的,是不会看到分类中新加的方法的,因为分类,跟原类 没有写在同一个object-c file里
//NSString就可以,因为系统把它所有的分类都写在了NSString这个file里了
-(NSInteger)getStarTime;
@end
*/
}