#import <objc/runtime.h>
1.先添加属性,但是不会动态生成带下划线的属性
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, copy) NSString *loginPwd;
@property (nonatomic , copy) void (^indexBlock)(NSInteger index);
2.
1>.如果是基本数据类型
static char strKey = 'm';
- (NSInteger)index{
return [objc_getAssociatedObject(self, &strKey) intValue];
}
- (void)setIndex:(NSInteger)index{
return objc_setAssociatedObject(self, &strKey, @(index), OBJC_ASSOCIATION_ASSIGN);
}
2>.如果是字符串,自定义对象
static void *str = &str;
-(void)setLoginPwd:(NSString *)loginPwd{
return objc_setAssociatedObject(self, & str, loginPwd, OBJC_ASSOCIATION_COPY);
}
- (NSString *)loginPwd{
return objc_getAssociatedObject(self, & str);
}
3>.如果是block类型,类似于字符串类型
static void *strKey3 = &strKey3;
-(void)setIndexBlock:(void (^)(NSInteger))indexBlock{
return objc_setAssociatedObject(self, & strKey3, indexBlock, OBJC_ASSOCIATION_COPY);
}
-(void (^)(NSInteger))indexBlock{
return objc_getAssociatedObject(self, & strKey3);
}