經(jīng)常聽(tīng)android的同事說(shuō)注解,說(shuō)這個(gè)技術(shù)真好用剂桥。好奇心之下忠烛,我也搜索了下ios的注解。完蛋权逗,ios的注解大多數(shù)都是講怎么注釋的美尸,根本沒(méi)有注解。我就在想我們ios上能不能也實(shí)現(xiàn)注解這個(gè)功能呢斟薇?想實(shí)現(xiàn)這個(gè)功能师坎,我們必須要懂得注解是個(gè)什么東西才行,因此我就詢(xún)問(wèn)同事和網(wǎng)上查資料堪滨,弄懂了注解到底是個(gè)啥東西胯陋。
注解
android 注解的解釋
注解(Annotaion),也叫元數(shù)據(jù)袱箱。一種代碼級(jí)別的說(shuō)明遏乔。它是JDK1.5及以后版本引入的一特性,與類(lèi)犯眠、接口按灶、枚舉是在同一個(gè)層次症革。它可以聲明在包筐咧、類(lèi)、字段噪矛、方法量蕊、局部變量、方法參數(shù)等的前面艇挨,用來(lái)對(duì)這些元素進(jìn)行說(shuō)明残炮、注解。
在我看來(lái)注解就是一個(gè)標(biāo)簽缩滨。用來(lái)標(biāo)示類(lèi)势就、字段泉瞻、方法等的特性。
注解分類(lèi)
根據(jù)聲明周期苞冯,android的注解分為三類(lèi)
- 源代碼注解
- 編譯時(shí)注解
- 運(yùn)行時(shí)注解
源代碼注解
主要作用是編譯檢查袖牙。
在編譯代碼之前就讓編譯器給你查閱代碼的合法性,相當(dāng)于ios上的類(lèi)型檢查。這個(gè)注解在編譯階段就沒(méi)用了舅锄。
這個(gè)暫時(shí)沒(méi)想到辦法能實(shí)現(xiàn)幫助編譯器做校驗(yàn)鞭达。
編譯時(shí)注解
在編譯階段讓編譯器主動(dòng)幫助我們生成一些類(lèi),而不用我們自己編寫(xiě)這些類(lèi)皇忿,我們只要告訴編譯器如何編譯這個(gè)類(lèi)就行了畴蹭。這個(gè)注解在編譯結(jié)束后已經(jīng)生成了我們所需要的代碼。
運(yùn)行時(shí)注解
在運(yùn)行時(shí)鳍烁,我們可以獲取類(lèi)叨襟,方法,屬性等我們給其打的注解(標(biāo)簽)幔荒,這個(gè)在程序啟動(dòng)的時(shí)候幫助我們綁定類(lèi)芹啥,方法,屬性铺峭。
以上是個(gè)人理解墓怀。不對(duì)的請(qǐng)各路大神指正。
從上面這幾種注解中卫键,源代碼注解傀履,我目前是沒(méi)有一點(diǎn)想實(shí)現(xiàn)的想法(無(wú)從下手)。編譯時(shí)注解莉炉,是在程序編譯階段幫助我們自動(dòng)生成一些文件添加到工程里面钓账,這個(gè)需要編譯器去做,貌似也做不了絮宁。能力所限梆暮,剩下的只能做個(gè)運(yùn)行時(shí)注解了。
運(yùn)行時(shí)注解
場(chǎng)景一:我們創(chuàng)建TableView绍昂, 有三項(xiàng)啦粹,每項(xiàng)都應(yīng)一個(gè)vc跳轉(zhuǎn),如果我們新增加一項(xiàng)或者刪除一項(xiàng)窘游,我們就需要修改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:^{
}];
}
如果我們需要再新增一個(gè)類(lèi)** OPFourViewController**,我們需要改動(dòng)代碼如下
#import "OPFourViewController.h"
[self.datasource addObject:[[OPFourViewController alloc]init]];
上面的寫(xiě)法肯定沒(méi)有問(wèn)題忍饰。
那用運(yùn)行時(shí)注解怎么做呢贪嫂?
我們創(chuàng)建一個(gè)注解類(lèi)
#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
我們?cè)诿總€(gè)類(lèi)的.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.
}
調(diào)用
NSSet * set = [OPVCAnnotion getVCWithType:@"UI"];
for (Class cls in set) {
[self.datasource addObject:[[cls.class alloc]init]];
}
ok 運(yùn)行項(xiàng)目
我們發(fā)現(xiàn),我們?cè)僖膊挥藐P(guān)心TableView的 dataSource艾蓝。
只要是我們給vc 添加了注解力崇,我們就能從OPVCAnnotion中獲取到斗塘。
運(yùn)行時(shí)注解實(shí)現(xiàn)
我們知道注解相當(dāng)于個(gè)標(biāo)簽,標(biāo)簽可以綁定類(lèi)亮靴,屬性或者方法逛拱。在運(yùn)行的時(shí)候運(yùn)行一段代碼,因此這段代碼只能在.m文件中了(.h文件不能有函數(shù)實(shí)現(xiàn))台猴。因此我們需要考慮的怎么在運(yùn)行時(shí)將類(lèi)朽合,屬性或者方法和標(biāo)簽進(jìn)行綁定,并且是在程序運(yùn)行的開(kāi)始階段就綁定饱狂。
第一種方案:是在+load 方法進(jìn)行綁定曹步。
第二種方案:是在attribute ((constructor)) 標(biāo)記的方法中綁定
這兩種方案都是在程序啟動(dòng),調(diào)用main函數(shù)之前調(diào)用的休讳,我拋棄了第一種方案讲婚,因?yàn)?load 方法,大家有時(shí)候需要用的嘛俊柔。第二種方案隨便命名筹麸,只要用attribute ((constructor)) 標(biāo)記就可以了。
因?yàn)樾枰?lèi)和注解之間綁定關(guān)系雏婶,我們這里采用單例類(lèi)來(lái)記錄類(lèi)和注解之間的綁定關(guān)系物赶。
關(guān)系圖
@interface OPAnnotationManager : NSObject
+(OPAnnotationManager *)shareOPAnnotationManager;
///類(lèi)注解
///增加一個(gè)類(lèi)注解
-(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 - 類(lèi)方法注解
-(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;
///如何實(shí)現(xiàn) 檢查類(lèi)型
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: 類(lèi) %@ 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
上述是單例類(lèi)的實(shí)現(xiàn),這里我們還創(chuàng)建了個(gè)Annotation類(lèi)留晚,就是為了圖中的那條虛線酵紫,我們可以通過(guò)類(lèi)找到注解,我們也應(yīng)該可以通過(guò)注解找到相關(guān)的類(lèi)错维,我們將類(lèi)給注解類(lèi)奖地,具體如何處理是我們自己的事情了。
如何添加注解呢赋焕?因?yàn)榭赡苡卸鄠€(gè)參數(shù)傳入参歹,因此我們這里采用宏定義的方式進(jìn)行處理
///類(lèi)注解
#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];\
}
獲取不定參數(shù)
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;
}
因?yàn)閷?shí)現(xiàn)起來(lái)不難,這里只是拋磚引玉隆判,希望各種大牛真正實(shí)現(xiàn)ios的注解犬庇。
源碼實(shí)現(xiàn)了屬性 ,類(lèi)和類(lèi)方法的注解蜜氨。