美文网首页
iOS利用runtime动态增加属性

iOS利用runtime动态增加属性

作者: 不简单的风度 | 来源:发表于2016-05-26 12:46 被阅读67次

导入头文件<objc/runtime.h>
本文主要使用UIView举例。
首先新建一个类别
.h文件


#import <UIKit/UIKit.h>

@interface UIView (name)

@property (nonatomic, copy) NSString *name;

@end

.m文件

#import "UIView+name.h"
#import <objc/runtime.h>

@implementation UIView (name)

static const char * UIViewName_Key = "UIViewName_Key";

- (void)setName:(NSString *)name {
    objc_setAssociatedObject(self, UIViewName_Key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)name {
    return objc_getAssociatedObject(self, UIViewName_Key);
}

@end

然后可以去ViewController中创建一个view试试

ViewController的.m文件

UIView *zzView = [[UIView alloc] init];
    zzView.name = @"leroy";
    NSLog(@"the view name is : %@",zzView.name);

控制台输出

2017-11-23 15:21:16.331 ImageDemo[74635:6925367] the view name is : leroy

以上就是利用runtime动态增加属性的过程。

相关文章

网友评论

      本文标题:iOS利用runtime动态增加属性

      本文链接:https://www.haomeiwen.com/subject/miqxdttx.html