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

来源:互联网 发布:初中英语软件哪个好 编辑:程序博客网 时间:2024/04/30 19:46
属性扩展主要用到用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


0 0
原创粉丝点击