当 IBAction 方法不是从操作中调用时使用它吗?
当实际未从用户操作中调用 IBAction 时,使用 IBAction 时是否存在任何问题?
如果您有类似的操作,
-(IBAction)sayHello:(id)sender;
您可以从类中调用它,例如:
[self sayHello:@"x"]
@“x”不执行任何操作,它只是填充发件人。
实际上,您可以创建一个没有 (id)sender 的 IBAction 方法
-(IBAction)sayHello;
,并从用户操作和代码中调用它,但是您将无法从界面获得任何有用的发件人信息。从代码调用时,填写发件人的“正确”方式是什么?您可以创建从代码中调用时发送的发件人信息吗?
只是想弄清楚。
Are there any issues when using IBAction when it is not actually called from a user's action?
If you have an action like
-(IBAction)sayHello:(id)sender;
You can call it from within your class like:
[self sayHello:@"x"]
The @"x" doesn't do anything, it just fills in for the sender.
You can actually create an IBAction method without (id)sender
-(IBAction)sayHello;
and call it from both user's actions and from within the code, but then you won't get any useful sender info from the interface. What's the 'correct' way of filling in for the sender, when calling from the code? And can you create sender info to send when it's called from within the code?
Just trying to figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为 OOP 的一个好的实践是折射方法
-(IBAction)sayHello:(id)发件人;
另一个名为:-(void)sayHello; 的方法
并在方法内部
-(IBAction)sayHello:(id)sender {
[自我打招呼];
如果
其他方法想要调用 sayHello:(id)sender 操作来完成某些工作,它可以调用 sayHello。方法名称应该有意义,以便客户端可以毫无问题地调用它或解决问题。当您需要测试或调试时它将帮助您
I think a good practice for OOP is to refractor the method
-(IBAction)sayHello:(id)sender;
to another method called: -(void)sayHello;
and inside the method
-(IBAction)sayHello:(id)sender {
[self sayHello];
}
If other methods want to call the sayHello:(id)sender action to do some job, it can call the sayHello. The method name should make sense for the client to call it without a problem or work around. It will help you when you have to test or debug
发送者应该是一个 UI 组件。因此,如果在你的类中你有一个 UIButton...
那么你可以将它作为参数发送给操作:
在方法内部,无论它是从 UI 调用还是以某种模拟方式调用,你都可以有一些逻辑来检测发件人是谁,并据此采取不同的行为。这样,多个按钮或其他组件可以重用相同的操作方法。
The sender should be a UI component. So if in your class you have, say, a UIButton...
Then you can just send it as parameter to the action:
Insider the method, no matter if it is called from the UI or in some simulated way, you can have some logic to detect who the sender is, and behave differently based on that. This way, multiple buttons or other components can reuse the same action method.
除非您实际上使用了
sender
参数(有关更多信息,请参阅 Jaanus 的答案),否则在从代码调用该方法时可以为其传递nil
。Unless you're actually making use of the
sender
parameter (see Jaanus's answer for more on that), you're fine with passingnil
for it when calling the method from code.