美文网首页
iOS - runtime category分类添加属性

iOS - runtime category分类添加属性

作者: 西半球_ | 来源:发表于2020-07-07 10:36 被阅读0次
 typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
     OBJC_ASSOCIATION_ASSIGN = 0,             //关联对象的属性是弱引用
     OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,   //关联对象的属性是强引用并且关联对象不使用原子性
     OBJC_ASSOCIATION_COPY_NONATOMIC = 3,     //关联对象的属性是copy并且关联对象不使用原子性
     OBJC_ASSOCIATION_RETAIN = 01401,         //关联对象的属性是copy并且关联对象使用原子性
     OBJC_ASSOCIATION_COPY = 01403            //关联对象的属性是copy并且关联对象使用原子性
 };

.h

#import "ViewController.h"

NS_ASSUME_NONNULL_BEGIN

@interface ViewController (aa)

@property (nonatomic, assign) int  currentIndex;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) NSString *title;

@end

NS_ASSUME_NONNULL_END

.m


#import "ViewController+ aa.h"
#import <objc/runtime.h> 
static NSString *currentIndexKey = @"currentIndexKey";
static NSString *titleKey = @"titleKey";

@implementation ViewController (aa)

/**
 
 typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
     OBJC_ASSOCIATION_ASSIGN = 0,             //关联对象的属性是弱引用
     OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,   //关联对象的属性是强引用并且关联对象不使用原子性
     OBJC_ASSOCIATION_COPY_NONATOMIC = 3,     //关联对象的属性是copy并且关联对象不使用原子性
     OBJC_ASSOCIATION_RETAIN = 01401,         //关联对象的属性是copy并且关联对象使用原子性
     OBJC_ASSOCIATION_COPY = 01403            //关联对象的属性是copy并且关联对象使用原子性
 };
 
 */

-(void)setCurrentIndex:(int)currentIndex{
    objc_setAssociatedObject(self, &currentIndexKey, @(currentIndex), OBJC_ASSOCIATION_ASSIGN);
}
-(int)currentIndex{
    return [objc_getAssociatedObject(self, &currentIndexKey) intValue];
}

- (void)setIndex:(NSInteger)index{
    objc_setAssociatedObject(self, @selector(currentIndex), @(index), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)index{
    return [objc_getAssociatedObject(self, _cmd) integerValue];
}

-(void)setTitle:(NSString *)title{
    objc_setAssociatedObject(self, &titleKey,title, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString *)title{
    return objc_getAssociatedObject(self, &titleKey);
}

相关文章

网友评论

      本文标题:iOS - runtime category分类添加属性

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