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, ¤tIndexKey, @(currentIndex), OBJC_ASSOCIATION_ASSIGN);
}
-(int)currentIndex{
return [objc_getAssociatedObject(self, ¤tIndexKey) 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);
}
网友评论