是<objc/runtime.h>
中 objc_getAssociatedObject
和 objc_setAssociatedObject
的包装器
这个库有一个重要的原因
您可以在自己的分类中添加自定义属性
只需将 NSObject+CJAAssociatedObject.h
和 NSObject+CJAAssociatedObject.m
文件拖放到您的项目中。
首先查看示例项目,特别是 UIViewController+ExampleCategory
分类。
static void *kExampleStringKey;
static void *kExampleBoolKey;
static void *kExampleFloatKey;
static void *kExampleDoubleKey;
- (void)yourMethod {
//Set a example String value for the given key
[self setAssociatedValue:@"Lorem ipsum" forKey:&kExampleStringKey];
//Gets the string value from the given key
NSString *exampleString = [self associatedValueForKey: &kExampleStringKey];
NSLog(@"example String %@", exampleString);
//Set a example BOOL value for the given key
[self setAssociatedBoolValue:YES forKey: &kExampleBoolKey];
//Gets the bool value from the given key
BOOL exampleBool = [self associatedBoolValueForKey: &kExampleBoolKey];
NSLog(@"example BOOL %d", exampleBool);
//Set a example float value for the given key
[self setAssociatedFloatValue:41.0f forKey: &kExampleFloatKey];
//Gets the float value from the given key
float exampleFloat = [self associatedFloatValueForKey: &kExampleFloatKey];
NSLog(@"example Float %f", exampleFloat);
//Set a example double value for the given key
[self setAssociatedDoubleValue: 37.37 forKey: &kExampleDoubleKey];
//Gets the double value from the given key
double exampleDouble = [self associatedDoubleValueForKey: &kExampleDoubleKey];
NSLog(@"example Double %f", exampleDouble);
}
在 MIT 许可证 下发布