利用RunTime中的objc_setAssociatedObject函数可以轻松做到
/**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.
* @param key The key for the association.
* @param value The value to associate with the key key for object. Pass nil to clear an existing association.
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
*
* @see objc_setAssociatedObject
* @see objc_removeAssociatedObjects
*/
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
以下是我项目中的代码
先将参数通过key绑定在btn上
TestMode1 *model1 = [[TestMode1 alloc]init];
TestMode2 *model2 = [[TestMode2 alloc]init];
objc_setAssociatedObject(self.popView.btnYES, "model1", model1, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(self.popView.btnYES, "model2", model2, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self.popView.btnYES addTarget:self action:@selector(changePeriod:) forControlEvents:UIControlEventTouchUpInside];
在点击事件函数中通过objc_getAssociatedObject将多个参数取出来即可
- (void)changePeriod:(UIButton *)btn{
[self removeTheTipView];
TestMode1 *m1 = objc_getAssociatedObject(btn, "model1");
TestMode2 *m2 = objc_getAssociatedObject(btn, "model2");
}
当然要是通过声明一个全局变量来传值也是可以的