OCAnnotation 是一个轻量级框架,它赋予 Objective-C 语言的注解能力。类似于 Java,注解是一种可以添加到源代码中的语法元数据形式。它提供了一种简单的方法,将某些行为应用于相关的程序元素,如类、方法等。通过嵌入这个特性,我们可以使 Objective-C 成为一个更加灵活的语言,并为我们带来更多便利和可能性。
该框架由蚂蚁财富软件开发团队开发和维护。它已应用于我们项目的多个模块,包括但不限于日志、网络层和数据层。我们希望与您分享这个精美工具,并期待您充分发挥想象力探索其用法。
gem install ocannotation
oca_setup
如果运行成功,您会得到类似以下的结果
pod 'OCAnnotation'
现在,一切准备就绪~
这个工具背后的神秘之处在于扫描您项目中的所有注解并进行建模。因此,在您的应用程序启动时,需要进行一些设置工作。以下是一个示例代码段:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
OCAAnnotationManager *annotationManager = [OCAAnnotationManager sharedManager];
// custom annotation type registration (optional)
[annotationManager registerAnnotationType:@"RemoteLog"
position:OCAAnnotationPositionMethod
class:[AFWRemoteLogMethodAnnotation class]];
// annotation setup
NSDictionary *configs = kAFWAnnotationConfigs; // using the macro name you write in the Annotation/.config file
[[OCAAnnotationManager sharedManager] addConfigsWithConfigDic:configs];
}
注意:扫描完成后,生成的文件(CustomFileName.gen.h)将被复制到您的项目路径。您需要使用 '将文件添加到...' 将文件引用添加到项目中,以便成功访问生成的宏。
“类型”是表示一组注解的特定类型的自定义变量。通常,类型与特定的使用场景相关。要创建自己的自定义注解类型,您需要为该类型创建一个注解类,并且该类应该是OCABaseAnnotation的子类。在OCAnnotation.framework中,OCABaseAnnotation是定义一些基本行为的基础注解模型类。我们还提供了OCABaseClassAnnotation/OCABaseMethodAnnotation/OCABasePropertyAnnotation,它们是附加到类/方法/属性的注解的基础模型。您也可以继承它们。如上节所述,您需要在启动时注册您自定义的类型。
// custom annotation type registration (optional)
[annotationManager registerAnnotationType:@"RemoteLog"
position:OCAAnnotationPositionMethod
class:[AFWRemoteLogMethodAnnotation class]];
在您的子类中,您可以在init方法中执行任何魔法,所有注解中的信息都已打包在变量'params'中供您使用。快速示例
- (instancetype)initWithSourceFile:(NSString *)sourceFile
className:(NSString *)className
params:(NSDictionary *)params
methodSelector:(NSString *)methodSelector
type:(NSString *)type
{
self = [super initWithSourceFile:sourceFile
className:className
params:params
methodSelector:methodSelector
type:type];
if (self) {
self.remoteLogId = self.parameters[@"remoteLogId"];
self.remoteLogMethod = self.parameters[@"remoteLogMethod"];
@weakify(self);
self.onAnnotationCreated = ^(OCABaseAnnotation *anno){
@strongify(self);
[self registerRemoteLogAOP];
};
}
return self;
}
在任何程序元素上方,您可以使用格式“#pragma annotation(key:"value")”添加您的注解。例如,如果您想要在@interface UIApplicationDelegate上添加注解(不同的键值对可以使用逗号或空格作为分隔符。键和值可以通过冒号或等号相关联)
#pragma annotation(type:"default",param1:"value1",param2:"value2")
@interface UIApplicationDelegate()
就这样。您已经成功地在@interface UIApplicationDelegate上添加了注解。
我们提供了一个名为OCAnnotationDemo的演示项目,其中展示了此工具的基本用法。欢迎您下载并尝试使用它。