1.可以通过关联对象机制把两个对象连起来。
2.定义关联对象时可指定内存管理语义,定义属性时采用的“拥有关系”与“非拥有关系”。3.只有在其他办法都没用的时候再引入关联对象,这种做法通常会产生难以查找的BUG。
关联策略
/** * OBJC_ASSOCIATION_ASSIGN 等价于@PRoperty (assign) , @property (unsafe_unretained) 弱引用关联对象 * OBJC_ASSOCIATION_RETAIN_NONATOMIC 等价于@property (strong, nonatomic) 强引用关联对象,且为非原子操作 * OBJC_ASSOCIATION_COPY_NONATOMIC 等价于@property (copy, nonatomic) 复制关联对象,且为非原子操作 * OBJC_ASSOCIATION_RETAIN 等价于@property (strong, atomic) 强引用关联对象,且为原子操作 * OBJC_ASSOCIATION_COPY 等价于@property (copy, atomic) 复制关联对象,且为原子操作 其中,第 2 种与第 4 种、第 3 种与第 5 种关联策略的唯一差别就在于操作是否具有原子性。 */ objc_setAssociatedObject(button, buttonKey, _imgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);例:
1、倒入头文件,声明key:
#import <objc/runtime.h>char* const buttonKey = "buttonKey";2、设置关联:if (groupModel.isOpened) { UIImageView * _imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, (44-16)/2, 14, 16)]; [_imgView setImage:[UIImage imageNamed:@"ico_list"]]; [sectionView addSubview:_imgView]; CGAffineTransform currentTransform = _imgView.transform; CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform, M_PI/2); // 在现在的基础上旋转指定角度 _imgView.transform = newTransform; objc_setAssociatedObject(button, buttonKey, _imgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); }else{ UIImageView * _imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, (44-16)/2, 14, 16)]; [_imgView setImage:[UIImage imageNamed:@"ico_list"]]; [sectionView addSubview:_imgView]; objc_setAssociatedObject(button, buttonKey, _imgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); }3、获取关联:- (void)buttonPress:(UIButton *)sender//headButton点击{ GroupModel *groupModel = dataSource[sender.tag]; UIImageView *imageView = objc_getAssociatedObject(sender,buttonKey); if (groupModel.isOpened) { [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{ CGAffineTransform currentTransform = imageView.transform; CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform, -M_PI/2); // 在现在的基础上旋转指定角度 imageView.transform = newTransform; } completion:^(BOOL finished) { }]; }else{ [UIView animateWithDuration:0.3 delay:0.0 options: UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionCurveLinear animations:^{ CGAffineTransform currentTransform = imageView.transform; CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform, M_PI/2); // 在现在的基础上旋转指定角度 imageView.transform = newTransform; } completion:^(BOOL finished) { }]; } groupModel.isOpened = !groupModel.isOpened; [expandTable reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];}
新闻热点
疑难解答