调用特定类中的方法
我目前正在这样做是为了向导航栏添加一个按钮来调用 SwitchViews 方法。
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back to App"
style:UIBarButtonItemStyleBordered
target:nil
action:@selector(switchViews:)];
self.navigationItem.leftBarButtonItem=backButton;
[backButton release];
这个方法恰好在另一个类(SwitchViewController)中,但它正在工作,因为我猜该方法调用会遍历响应者链,直到在 SwitchViewController 中找到它。
有什么方法可以将目标设置为我的班级而不是零?
我想这会让代码更容易阅读、调试和维护。
我确信这对于一些比我更有经验的程序员来说是一个简单的答案......
谢谢
I'm currently doing this to add a button to my navigation bar to call the SwitchViews method.
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back to App"
style:UIBarButtonItemStyleBordered
target:nil
action:@selector(switchViews:)];
self.navigationItem.leftBarButtonItem=backButton;
[backButton release];
This method happens to be in another class (SwitchViewController) but it is working as I guess the method call goes through the responder chain until it finds it in SwitchViewController.
Is there any way that I can set the target to my class instead of nil?
Guess that would make the code easier to read, debug and maintain.
I'm sure it's a simple answer to some more experienced programmers than me...
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将将目标设置为零显然会导致操作被发送到响应者链。不知道。target
设置为nil
理论上应该根本不起作用,但也许正如你所说,它会用它做一些智能的事情。要将其设置为您的类,您首先需要对所述类的引用。谁主持这个班级?应用程序代表?应用程序委托是否可以将该类的引用移交给该类(因为它需要它)?如果此类以编程方式初始化,您甚至可以调整
init
方法以采用新参数(类)。包含上述代码片段的方法是什么样的?它是一个初始化方法吗? viewDidLoad 方法?
如果它是一个 init 方法并且是从 NIB 文件调用的(即它是
initWithCoder:
),那么您最好的选择可能是直接从应用程序委托中获取引用,使用上面假设您已经为
THATCLASS
正确设置@property
(这是您想要的目标
),例如SettingSetting target to nil apparently results in the action being sent up the responder chain. Didn't know that.target
tonil
should, in theory, not work at all, but maybe it does some intelligent stuff with it as you say.To set it to your class, you first need a reference to said class. Who holds that class? The application delegate? Could the application delegate hand that class's reference over to this class, since it needs it? If this class is initialized programmatically, you could even tweak the
init
method to take a new argument (the class).What does the method which has the above code snippet in it look like? Is it an init method? A viewDidLoad method?
If it's an init method and it's called from a NIB file (i.e. it's
initWithCoder:
) then your best bet might be to simply grab the reference directly from the application delegate, usingThe above presumes that you've properly set up a
@property
forTHATCLASS
(which is your intendedtarget
), e.g.