UIButton addTarget:self action:@selector() 傳多個引數

weixin_34402408發表於2017-03-03

利用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");

}

當然要是通過宣告一個全域性變數來傳值也是可以的

相關文章