利用RunTime中的objc_setAssociatedObject函數(shù)可以輕松做到
/**
* 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);
以下是我項(xiàng)目中的代碼
先將參數(shù)通過(guò)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];
在點(diǎn)擊事件函數(shù)中通過(guò)objc_getAssociatedObject將多個(gè)參數(shù)取出來(lái)即可
- (void)changePeriod:(UIButton *)btn{
[self removeTheTipView];
TestMode1 *m1 = objc_getAssociatedObject(btn, "model1");
TestMode2 *m2 = objc_getAssociatedObject(btn, "model2");
}
當(dāng)然要是通過(guò)聲明一個(gè)全局變量來(lái)傳值也是可以的