开发者

How to send parameters to a selector?

I know to send a parameter to a selector, we use withObject, but how to handle the following case:

 UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:[[NavigatorUtil new] autorelease] action:@selector(back:) ];

The back method looks like:

#import "NavigationUtil.h"

@implementation NavigationUtil

+(void) back: (UINavigationController*) navigationController开发者_运维问答
{
    [navigationController popViewControllerAnimated:YES];
}

@end

Now I need to send a parameter to this selector? How to?


What do you mean "send a parameter to this selector"? This phrase doesn't compute.

It seams to me you should RTFM a little, for example the Event Handling Guide for iOS.

In short, the button's "action" is a message that the button sends to its target. In Objective-C, a message is defined by its selector, which can more or less be seen as the method name and signature.

The button knows about three signatures for this selector: zero, one or two arguments. In your case, you use a method with one argument. You can't decide what it's going to be. This argument is always the same. It's going to be the sender, i.e. the button itself.

So that's problem #1 with your action method.

Problem #2 with your action method is that you defined it as a class method. It should be an instance method.

Now finally, if you want to reach the UINavigationController from the NavigatonUtil, you need to find another way. For example to store it beforehand as an instance variable.


When providing selectors as the action, you typically rely on member (iVar) variables.

In your case, store the navigation controller as an iVar and then reference it from your selectors action.

Also, you're setting it up as a code but in case you ever want to bind that method as an action in interface builder, you should make it return IBAction which the compilers resolves to void but it's a hint to interface builder. Notice it shouldn't be a class method either.

- (IBAction) back
{
    [[self _navigationController] popViewControllerAnimated:YES];
}

Another option you could look into is blocks which allow for sending methods with parameters or inline providing a block of code which also helps when you want to avoid member state (for example async/concurrent code).

Checkout this SO article:

UIButton block equivalent to addTarget:action:forControlEvents: method?

Hope that helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜