I have the following code that updates the value of a textfield with the current time. My question is: Why do you send nil as the sender at the bottom part of the code? [self showCurrentTime:nil];
CurrentTimeViewController.m
- (IBAction)showCurrentTime:(id)sender
{
NSDate *now = [NSDate date];
static NSDateFormatter *formatter = nil;
if(!formatter) {
formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
}
[timeLabel setText:[formatter stringFromDate:now]];
}
…
- (void)viewWillAppear:(BOOL)animated
{
NSLog(@"CurrentTimeViewController will appear");
[super viewWillAppear:animated];
[self showCurrentTime:nil];
}
Because normally when action handlers are called, they pass the object that initiated the call to the method, like a
UIButton, orUISegmentedControl. But, when you want to call the method from your code, and not as the result of an action, you cannot pass a human assender, so you passnil.Also, the
- (IBAction)indicates that this method can be connected to an event via theInterface Builderby dragging aTouch Up Inside(or touch down outside/etc) event from a button (or any other control that has some sort of event) to theFile's Ownerand selectingthumbTapped:.For example:
When the touch is released (and the touch is still inside the button), will call
thumbTapped:, passing thebuttonobject as thesender