您的位置:首页 > 编程语言 > Go语言

通过objc runtime 为类别(Category)动态增加属性

2015-03-26 16:03 489 查看
属性扩展主要用到用OC,APi中函数:objc_setAssociatedObject,objc_getAssociatedObject

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

方法扩展用category

首先导入头文件:#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: