在右栏按钮项的选择器中传递参数

时间:2012-09-26 09:42:54

标签: objective-c ios selector

我有这段代码:

UIBarButtonItem *donebutton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonPressed:)];
    self.navigationItem.rightBarButtonItem = donebutton;

现在我想将一些参数传递给方法:

- (void)doneButtonPressed{}

怎么做?

4 个答案:

答案 0 :(得分:5)

如果你想传递object say string,那么使用 setAssociatedObject

首先添加

#import <objc/runtime.h>

现在

NSString *strText = @"text";

 objc_setAssociatedObject(donebutton, "Argument", strText, OBJC_ASSOCIATION_RETAIN_NONATOMIC); // provide button , key , object for passing

并在任何你想要你的论点的地方检索:

NSString *str = objc_getAssociatedObject(donebutton, "Argument"); //using button and key
//remove object associated for button if not needed.

但如果你想要按钮参考,那么

- (void)doneButtonPressed:(id)sender{
  UIButton *btnClicked = (UIButton *)sender;
  .......
}

答案 1 :(得分:2)

你不能直接这样做。您应该将参数存储在类中其他位置的对象中,然后在点击按钮时将其检索。

例如,如果要传递NSString,请在.h中添加一个:

@interface myClass {

    NSString *param;
}

在你的.m:

- (void)doneButtonPressed {

    // Do something with param
}

答案 2 :(得分:1)

正如你所说的那样选择:

@selector(doneButtonPressed:)

它会崩溃,因为你的方法如下:

- (void)doneButtonPressed{}

但应该是:

- (void)doneButtonPressed:(id)sender{}

您可以通过发件人的代码传递数据,例如......

答案 3 :(得分:0)

可以在 UIBarButtonItem 的情况下使用的小hack是使用 possibleTitles 属性,该属性实际上是一种 NSSet&lt; NSSString *&gt; ,这意味着您可以在其中存储NSString以便以后检索它。

以下是如何做到的:

db.products.aggregate([ 
    { "$match" : { "_id": ObjectId("57c6957fb190ecc02e8b456b") } },
    { "$unwind": "$categories" },
    {
        "$lookup": {
            from : 'sale',
            localField: 'categories', 
            foreignField: 'saleCategoryId', 
            as : 'pcSales'  
        }
    }
]);

注意: possibleTitles 属性的实际用法解释为$lookup。这只是一个小小的黑客:)