开发者

Working backwards from null

I know that once you get better开发者_运维知识库 at coding you know what variables are and null popping out here and there may not occur. On the way to that state of mind are there any methods to corner your variable that's claiming to be null and verify that it is indeed null, or you just using the wrong code?

Example:

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

Button Name: (null) is what shows up in the console

Thanks


According to Apple's docs, the value for currentTitle may be nil. It may just not be set.

You can always do if (myObject == nil) to check, or in this case:

-(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);
  }
}

Another way to check if the back or forward button is pressed, is check the id itself.

//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");
  }
}

also, make sure your outlets and actions are all connected in IB, and that you save and re-build the project. I've gone where I changed somehting in IB, saved the .m file (not the nib) and was like "why isn't this working???"


I was using the wrong field in Interface Builder I was using Name from the Interface Builder Identity instead of Title from the button settings.


buttonName cannot be null, otherwise buttonName.currentTitle would produce an error.

Therefore the currentTitle attribute itself must be null.

Or, maybe currentTitle is a string with the value (null).

In general, in Objective-C, if you have [[[myObject aMethod] anotherMethod] xyz] and the result is null it's difficult to know which method returned null. But with the dot syntax . that's not the case.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜