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

属性扩展主要用到用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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值