通过objc runtime 为类别(Category)动态增加属性
来源:互联网 发布:初中英语软件哪个好 编辑:程序博客网 时间:2024/04/30 19:46
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)id objc_getAssociatedObject(id object, const void *key)原理详细参见官方的https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html
首先导入头文件:#import <objc/runtime.h>
示例一
看一个类别和动态添加属性的例子:
UILabel+Associate.h
#import <UIKit/UIKit.h>
@interface UILabel (Associate)
- (void) setFlashColor:(UIColor *) flashColor;
- (UIColor *) getFlashColor;
@end
UILabel+Associate.m
#import "UILabel+Associate.h"
#import <objc/runtime.h>
@implementation UILabel (Associate)
static char flashColorKey;//设置 key
- (void) setFlashColor:(UIColor *) flashColor{
objc_setAssociatedObject(self, &flashColorKey, flashColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIColor *) getFlashColor{
return objc_getAssociatedObject(self, &flashColorKey);
}
@end
调用代码:
UILabel *lab = [[UILabel alloc] init];
[lab setFlashColor:[UIColor redColor]];
NSLog(@"%@", [lab getFlashColor]);
------------------------------
示例二
static char overviewKey;//设置 key
- (IBAction)showAlertAction:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"warn" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
objc_setAssociatedObject(alert, &overviewKey, @"test", OBJC_ASSOCIATION_RETAIN);
[alert show];
[alert release];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
NSLog(@"== : %@",objc_getAssociatedObject(alertView, &overviewKey));
}
}
打印输出
test
- 通过objc runtime 为类别(Category)动态增加属性
- objc runtime 动态增加属性
- objc runtime 动态增加属性
- objc runtime 动态增加属性
- objc runtime 动态增加属性
- KVO的使用以及 objc runtime 动态增加属性
- runtime结合category和block动态增加方法以及属性
- 59.通过 runtime为Category添加属性与成员变量
- iOS在分类中添加属性,运行时编程,objc runtime 动态增加属性
- objc之利用runtime为category添加成员变量
- 通过 objc_setAssociatedObject (关联) 的形式实现为Category (类别) 添加属性
- IOS通过runtime给category添加属性
- iOS (Category)runtime动态添加属性
- 利用Runtime为Category添加属性
- Runtime(三)利用运行时来为类别添加属性
- iOS为类别添加属性的方法(RunTime)
- 给category增加属性
- 给category增加属性
- 云计算网络珠玑
- vs2013安装AnkhSVN,但是不起作用解决方法
- Derby 配置和管理
- Eclipse快捷键大全(在其他IDE上也可以用)
- Android Universal Image Loader 源码分析
- 通过objc runtime 为类别(Category)动态增加属性
- RTSP回放时如何通过RTP的timestamp计算npt时间
- 正则表达式30分钟入门教程
- Dagger 源码解析
- poj1047 高精度
- cocos2d-x v3.3 Hide and Show
- Java语言的运行机制
- datetime为空的情况
- jQuery常用选择器示例