当 IBAction 方法不是从操作中调用时使用它吗?

发布于 2024-09-05 12:59:59 字数 431 浏览 6 评论 0原文

当实际未从用户操作中调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

戈亓 2024-09-12 12:59:59

我认为 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

〗斷ホ乔殘χμё〖 2024-09-12 12:59:59

发送者应该是一个 UI 组件。因此,如果在你的类中你有一个 UIButton...

UIButton *button;

那么你可以将它作为参数发送给操作:

[self sayHello:button];

在方法内部,无论它是从 UI 调用还是以某种模拟方式调用,你都可以有一些逻辑来检测发件人是谁,并据此采取不同的行为。这样,多个按钮或其他组件可以重用相同的操作方法。

The sender should be a UI component. So if in your class you have, say, a UIButton...

UIButton *button;

Then you can just send it as parameter to the action:

[self sayHello:button];

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.

垂暮老矣 2024-09-12 12:59:59

除非您实际上使用了 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 passing nil for it when calling the method from code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文