码迷,mamicode.com
首页 > 其他好文 > 详细

runtime动态添加属性

时间:2015-03-03 15:14:26      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">使用运行时库,必须要先引入 objc/runtime.h</span>
<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">看一个类别和动态添加属性的例子
UILabel+Associate.h
#import <UIKit/UIKit.h>
@interface UILabel (Associate)

- (void) setFlashColor:(UIColor *) flashColor;

- (UIColor *) getFlashColor;


</span>
<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">@end</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">UILabel+Associate.m</span>

<span style="font-family: Arial, Helvetica, sans-serif;">#import "UILabel+Associate.h"</span>
#import <objc/runtime.h>

@implementation UILabel (Associate)

static char flashColorKey;

- (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]);



runtime动态添加属性

标签:

原文地址:http://blog.csdn.net/qinguo2000/article/details/44037849

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!