对象关联类型
关联类型 | 等效的@property属性 |
---|---|
OBJC_ASSOCIATION_ASSIGN | assign |
OBJC_ASSOCIATION_RETAIN_NONATOMIC | nonatomic,retain |
OBJC_ASSOCIATION_COPY_NONATOMIC | nonatomic,copy |
OBJC_ASSOCIATION_RETAIN | retain |
OBJC_ASSOCIATION_COPY | copy |
管理关联对象的方法:
objc_setAssociatedObject(id object, void * key, id value, <objc_AssociationPolicy policy)
以给定的key为对象设置关联对象的value
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
根据key从对象中获取相应的关联对象的value
objc_removeAssociatedObjects(id _Nonnull object)
移除所有关联对象
使用时通常使用静态的全局变量做key
demo:
static void *MKEAlterViewKey = "MKEAlterViewKey";
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"123" message:@"345" delegate:self cancelButtonTitle:@"cancels" otherButtonTitles:@"jixu", nil];
void (^block)(NSInteger) = ^(NSInteger buttonIndex){ };
//block 为value MKEAlterViewKey为key 与对象alert关联
objc_setAssociatedObject(alert, MKEAlterViewKey, block, OBJC_ASSOCIATION_COPY);
[alert show];
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//获取value
void (^blcok)(NSInteger) = objc_getAssociatedObject(alertView, MKEAlterViewKey);
blcok(buttonIndex);
}
网友评论