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];}
新聞熱點
疑難解答