添加一个 attachment 属性到 NSObject, 这样你就可以为任意一个NSObject 子类添加附带的数据了,特别是针对需要异步传数据的情况,很方便。
@interface NSObject (Attachment)
@property (nonatomic, strong) id attachment;
@end
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:[UIColor clearColor]];
button.attachment = <your data>;
[button addTarget:self action:@selector(handleTap:) forControlEvents:UIControlEventTouchUpInside];
- (void)handleTap:(id)sender {
UIButton *button = (UIButton*)sender;
id <your data> = button.attachment;
//
}
attachment 的settter 和 getter 不是线程安全的,多线程问题,需要在调用的地方处理。