运行时+给分类添加属性

2019-08-16  本文已影响0人  Frankkkkk

运行时应用场景

具体使用

以创建UIImageView的分类为例,给UIImageView类添加一个urlStr属性。
1、新建分类fkWebImage分类
2、分类代码
2.1 .h添加需要的属性

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIImageView (fkWebImage)
@property (nonatomic, copy) NSString *urlStr;
@end

NS_ASSUME_NONNULL_END

2.2 .m导入头文件<objc/runtime.h>
2.3 重写urlStr的set和get方法,代码如下

#import "UIImageView+fkWebImage.h"
#import <objc/runtime.h>

@implementation UIImageView (fkWebImage)

const void *fk_urlKey = "fk_urlKey";
 
- (void)setUrlStr:(NSString *)urlStr {
    objc_setAssociatedObject(self, fk_urlKey, urlStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)urlStr {
    return objc_getAssociatedObject(self, fk_urlKey);
}

@end

3、外部测试

#import "ViewController.h"
#import "UIImageView+fkWebImage.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.urlStr = @"http://www.baidu.com/abc.jpg";
    NSLog(@"%@", imageView.urlStr);
}
上一篇 下一篇

猜你喜欢

热点阅读