【问题标题】:Working backwards from null从 null 向后工作
【发布时间】:2023-03-19 00:35:01
【问题描述】:

我知道,一旦你在编码方面变得更好,你就会知道什么是变量,并且这里可能会出现 null 并且可能不会出现。在达到这种心态的过程中,是否有任何方法可以使您声称为 null 的变量陷入困境并验证它确实为 null,或者您只是使用了错误的代码?

例子:

-(IBAction) startMotion: (id)sender {
    NSLog(@"Forward or back button is being pressed.");
    UIButton * buttonName = (UIButton *) sender;
    NSLog(@"Button Name:  %@", buttonName.currentTitle);
}

按钮名称:(null) 是显示在控制台中的内容

谢谢

【问题讨论】:

  • 这是...目标C?您可能应该将您的目标语言添加到标签中,以便最了解该语言的人可以帮助您。

标签: objective-c variables casting null


【解决方案1】:

According to Apple's docs, the value for currentTitle may be nil.可能只是没有设置。

您可以随时使用if (myObject == nil) 进行检查,或者在这种情况下:

-(IBAction) startMotion: (id)sender {
  NSLog(@"Forward or back button is being pressed.");
  UIButton * buttonName = (UIButton *) sender;
  if (buttonName != nil) {
    NSString *title = buttonName.currentTitle;
    NSLog(@"Button Name:  %@", title);
  }
}

另一种检查是否按下后退或前进按钮的方法是检查id 本身。

//in the interface, and connect it up in IB
//IBOutlet UIButton *fwdButton;
//IBOutlet UIButton *bckButton;

-(IBAction) startMotion: (id)sender {
  NSLog(@"Forward or back button is being pressed.");
  UIButton * buttonName = (UIButton *) sender;
  if (buttonName == fwdButton) {
    NSLog(@"FWD Button");
  }

  if (buttonName == bckButton) {
    NSLog(@"BCK Button");
  }
}

另外,请确保您的出口和操作都在 IB 中连接,并且您保存并重新构建项目。我去了我在 IB 中更改了一些东西的地方,保存了 .m 文件(不是笔尖)并且就像“为什么这不起作用???”

【讨论】:

    【解决方案2】:

    我在 Interface Builder 中使用了错误的字段 我使用的是 Interface Builder Identity 中的 Name 而不是按钮设置中的 Title。

    【讨论】:

      【解决方案3】:

      buttonName 不能为空,否则buttonName.currentTitle 会产生错误。

      因此currentTitle 属性本身必须为空。

      或者,也许currentTitle 是一个值为(null) 的字符串。

      一般来说,在 Objective-C 中,如果你有 [[[myObject aMethod] anotherMethod] xyz] 并且结果是 null 很难知道哪个方法返回 null。但是使用点语法. 并非如此。

      【讨论】:

      • 错了。 buttonName.currentTitle 只是 [buttonName currentTitle] 的不同写法,只是发送不带任何参数的消息的不同语法。由于您可以安全地向nil 发送消息(然后返回nil 或0 或0.0 或NULL),buttonName 也可以是nil
      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多