gpt4 book ai didi

iphone - (id)sender = nil?

转载 作者:行者123 更新时间:2023-12-01 17:27:45 27 4
gpt4 key购买 nike

我有以下代码用当前时间更新文本字段的值。我的问题是:为什么在代码的底部发送 nil 作为发件人? [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];
}

最佳答案

因为通常在调用 Action 处理程序时,它们会将发起调用的对象传递给方法,例如 UIButton , 或 UISegmentedControl .但是,当您想从代码中调用方法时,而不是作为操作的结果,您不能将人类作为 sender 传递。 , 所以你通过 nil .

此外,- (IBAction)表示此方法可以通过 Interface Builder 连接到事件通过拖动 Touch Up Inside (或触碰外部/等)事件从按钮(或任何其他具有某种事件的控件)到 File's Owner并选择 thumbTapped: .

例如:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = 1001;
[button addTarget:self action:@selector(thumbTapped:) forControlEvents:UIControlEventTouchUpInside];

当触摸被释放(并且触摸仍在按钮内部)时,将调用 thumbTapped: ,通过 button对象为 sender
- (IBAction)thumbTapped:(id)sender {
if ([sender isKindOfClass:[UIButton class]] && ((UIButton *)sender).tag == 1001) {
iPhoneImagePreviewViewController *previewVC = [[iPhoneImagePreviewViewController alloc] initWithNibName:@"iPhoneImagePreviewViewController" bundle:nil];
[self.navigationController pushViewController:previewVC animated:YES];
[previewVC release];
} else {
[[[[UIAlertView alloc] initWithTitle:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]
message:@"This method was called from somewhere in user code, not as the result of an action!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease] show];
}
}

关于iphone - (id)sender = nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7623120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com