經常聽android的同事說注解,說這個技術真好用。好奇心之下,我也搜索了下ios的注解。完蛋,ios的注解大多數都是講怎么注釋的,根本沒有注解。我就在想我們ios上能不能也實現注解這個功能呢?想實現這個功能,我們必須要懂得注解是個什么東西才行,因此我就詢問同事和網上查資料,弄懂了注解到底是個啥東西。
注解
android 注解的解釋
注解(Annotaion),也叫元數據。一種代碼級別的說明。它是JDK1.5及以后版本引入的一特性,與類、接口、枚舉是在同一個層次。它可以聲明在包、類、字段、方法、局部變量、方法參數等的前面,用來對這些元素進行說明、注解。
在我看來注解就是一個標簽。用來標示類、字段、方法等的特性。
注解分類
根據聲明周期,android的注解分為三類
- 源代碼注解
- 編譯時注解
- 運行時注解
源代碼注解
主要作用是編譯檢查。
在編譯代碼之前就讓編譯器給你查閱代碼的合法性,相當于ios上的類型檢查。這個注解在編譯階段就沒用了。
這個暫時沒想到辦法能實現幫助編譯器做校驗。
編譯時注解
在編譯階段讓編譯器主動幫助我們生成一些類,而不用我們自己編寫這些類,我們只要告訴編譯器如何編譯這個類就行了。這個注解在編譯結束后已經生成了我們所需要的代碼。
運行時注解
在運行時,我們可以獲取類,方法,屬性等我們給其打的注解(標簽),這個在程序啟動的時候幫助我們綁定類,方法,屬性。
以上是個人理解。不對的請各路大神指正。
從上面這幾種注解中,源代碼注解,我目前是沒有一點想實現的想法(無從下手)。編譯時注解,是在程序編譯階段幫助我們自動生成一些文件添加到工程里面,這個需要編譯器去做,貌似也做不了。能力所限,剩下的只能做個運行時注解了。
運行時注解
場景一:我們創建TableView, 有三項,每項都應一個vc跳轉,如果我們新增加一項或者刪除一項,我們就需要修改TableView,所在文件的代碼。
如下
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) NSMutableArray *datasource;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITableView * table= [[UITableView alloc]initWithFrame: [UIScreen mainScreen].bounds style:0];
table.delegate = self;
table.dataSource = self;
self.datasource = [NSMutableArray array];
[table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"vc"];
[self.datasource addObject:[[OPFirstViewController alloc]init]];
[self.datasource addObject:[[OPTwoViewController alloc]init]];
[self.datasource addObject:[[OPThirdViewController alloc]init]];
[self.view addSubview:table];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"vc"];
if (cell) {
cell.textLabel.text = NSStringFromClass([[self.datasource objectAtIndex:indexPath.row] class]);
}
return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.datasource.count;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self presentViewController:[self.datasource objectAtIndex:indexPath.row] animated:YES completion:^{
}];
}
如果我們需要再新增一個類** OPFourViewController**,我們需要改動代碼如下
#import "OPFourViewController.h"
[self.datasource addObject:[[OPFourViewController alloc]init]];
上面的寫法肯定沒有問題。
那用運行時注解怎么做呢?
我們創建一個注解類
#import "OPBaseAnnotation.h"
@interface OPVCAnnotion : OPBaseAnnotation
@property (nonatomic,strong) NSString *type;
@property (nonatomic,strong) NSString *name;
+(NSSet *)getVCWithType:(NSString *)type;
@end
#import "OPVCAnnotion.h"
static NSMutableDictionary * vcDic;
@implementation OPVCAnnotion
- (instancetype)init
{
self = [super init];
if (self) {
}
return self;
}
-(OPAnnotationQualifiedType)getAnnotationQualifiedType{
return OPAnnotationQualifiedClass;
}
+(NSSet *)getVCWithType:(NSString *)type{
if (!vcDic) {
return nil;
}
NSDictionary * dicName = [vcDic objectForKey:@"type"];
if (dicName) {
return [dicName objectForKey:type];
}
return nil;
}
-(OPBaseAnnotation *(^)(id))build{
return ^OPBaseAnnotation*(id object){
if (!self.type) {
return self;
}
if (!vcDic) {
vcDic = [NSMutableDictionary dictionary];
}
// self.name
NSMutableDictionary * clsDic = [vcDic objectForKey:@"type"];
if (!clsDic) {
clsDic = [NSMutableDictionary new];
[vcDic setObject:clsDic forKey:@"type"];
}
NSMutableSet * set = [clsDic objectForKey:self.type];
if (!set) {
set = [NSMutableSet new];
[clsDic setObject:set forKey:self.type];
}
[set addObject:object];
return self;
};
}
@end
我們在每個類的.m 文件中加入我們需要的注解
#import "OPFirstViewController.h"
#import "OPHead.h"
#import "OPVCAnnotion.h"
OPClassAnnotation(OPFirstViewController, OPVCAnnotion,@"type=UI",@"name=firstVC");
@interface OPFirstViewController ()
@end
@implementation OPFirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
調用
NSSet * set = [OPVCAnnotion getVCWithType:@"UI"];
for (Class cls in set) {
[self.datasource addObject:[[cls.class alloc]init]];
}
ok 運行項目
我們發現,我們再也不用關心TableView的 dataSource。
只要是我們給vc 添加了注解,我們就能從OPVCAnnotion中獲取到。
運行時注解實現
我們知道注解相當于個標簽,標簽可以綁定類,屬性或者方法。在運行的時候運行一段代碼,因此這段代碼只能在.m文件中了(.h文件不能有函數實現)。因此我們需要考慮的怎么在運行時將類,屬性或者方法和標簽進行綁定,并且是在程序運行的開始階段就綁定。
第一種方案:是在+load 方法進行綁定。
第二種方案:是在attribute ((constructor)) 標記的方法中綁定
這兩種方案都是在程序啟動,調用main函數之前調用的,我拋棄了第一種方案,因為+load 方法,大家有時候需要用的嘛。第二種方案隨便命名,只要用attribute ((constructor)) 標記就可以了。
因為需要類和注解之間綁定關系,我們這里采用單例類來記錄類和注解之間的綁定關系。
關系圖
@interface OPAnnotationManager : NSObject
+(OPAnnotationManager *)shareOPAnnotationManager;
///類注解
///增加一個類注解
-(void)addClass:(Class)cls AnnotationCls:(Class)annotation annotationParams:(NSDictionary *)params;
@interface OPAnnotationManager()
@property (nonatomic,strong) NSMutableDictionary *annationClsDic;
@end
@implementation OPAnnotationManager
static OPAnnotationManager * manager = nil;
+(OPAnnotationManager *)shareOPAnnotationManager{
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
manager = [[OPAnnotationManager alloc]init];
});
return manager;
}
- (instancetype)init
{
self = [super init];
if (self) {
self.annationClsDic = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark - 類方法注解
-(void)addClass:(Class)cls AnnotationCls:(Class)annotation annotationParams:(NSDictionary *)params{
NSString * clsStr = NSStringFromClass(cls);
NSMutableSet * set = [self.annationClsDic objectForKey:clsStr];
if (!set) {
set = [NSMutableSet set];
[self.annationClsDic setObject:set forKey:clsStr];
}
Class annotationCls = annotation;
///如何實現 檢查類型
OPBaseAnnotation* ann= [[annotationCls.class alloc]init];
if (!((ann.getAnnotationQualifiedType & OPAnnotationQualifiedClass)==OPAnnotationQualifiedClass)) {
OPLog(@"OPAnnotation: Annation %@ not qualifiedClass %@",annotation,clsStr);
return;
}
for (NSString * key in params) {
@try {
[ann setValue:params[key] forKey:key];
} @catch (NSException *exception) {
OPLog(@"OPAnnotation: 類 %@ Annation %@ not key %@",clsStr,annotation,key);
} @finally {
} }
if (ann.build){
ann.build(cls);
}
[set addObject:ann];
}
typedef enum : NSUInteger {
OPAnnotationQualifiedNone=0,
OPAnnotationQualifiedClass=1<<1,
OPAnnotationQualifiedProperty=1<<2,
OPAnnotationQualifiedMethod=1<<3,
OPAnnotationQualifiedMask=0x00FF,
} OPAnnotationQualifiedType;
@interface OPBaseAnnotation : NSObject
-(OPBaseAnnotation*(^)(id object))build;
-(OPAnnotationQualifiedType)getAnnotationQualifiedType;
@end
#import "OPBaseAnnotation.h"
@implementation OPBaseAnnotation
-(OPAnnotationQualifiedType)getAnnotationQualifiedType{
return OPAnnotationQualifiedNone;
}
-(OPBaseAnnotation*(^)(id object))build{
return ^(id object){
return self;
};
}
@end
上述是單例類的實現,這里我們還創建了個Annotation類,就是為了圖中的那條虛線,我們可以通過類找到注解,我們也應該可以通過注解找到相關的類,我們將類給注解類,具體如何處理是我們自己的事情了。
如何添加注解呢?因為可能有多個參數傳入,因此我們這里采用宏定義的方式進行處理
///類注解
#define OPClassAnnotation(ClassA,AnnotionClassA,...) __OPClassAnnotation(ClassA,AnnotionClassA,##__VA_ARGS__,10,9,8,7,6,5,4,3,2,1,0)
#define __OPClassAnnotation(ClassA,AnnotionClassA,_1, _2,_3,_4,_5,_6,_7,_8,_9,_10, N, ...) \
void __attribute__ ((constructor)) OPclassAnnotation##ClassA##AnnotionClassA##func(){ \
NSDictionary *params=nil;\
if (N==0){\
}else{\
params =__OPAnnotationParams(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N);\
}\
[[OPAnnotationManager shareOPAnnotationManager] addClass:ClassA.class AnnotationCls:AnnotionClassA.class annotationParams:params];\
}
獲取不定參數
NSDictionary * __OPGetAnnotationParamsDic(NSUInteger count, ...) {
NSMutableDictionary *paramDic = [NSMutableDictionary new];
va_list args;
va_start(args, count);
for (NSUInteger x = 0; x < count; ++x){
NSString * paramStr = va_arg(args, id);
NSArray * paramArr = [paramStr componentsSeparatedByString:@"="];
if (paramArr.count==2) {
[paramDic setObject:paramArr[1] forKey:paramArr[0]];
}
}
va_end(args);
return paramDic;
}
因為實現起來不難,這里只是拋磚引玉,希望各種大牛真正實現ios的注解。
源碼實現了屬性 ,類和類方法的注解。