我有代码来制作它,以便在按下按钮时弹出通知。我希望它在10秒钟后出现。
我知道我需要这样做:
(NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds invocation:
(NSInvocation *)invocation repeats:(BOOL)repeats
我的行动是:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlertView"
message:[NSString stringWithFormat:@"%d", hi]
delegate:hi
cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
[alert show];
}
答案 0 :(得分:1)
你可以这样做:
[self performSelector:@selector(actionMethodName) withObject:nil afterDelay:10];
如果用真正的方法名替换actionMethodName
。
如果你想使用定时器路由(这也是完全有效的),使用scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
比创建调用更容易。如果这样做,请保留对计时器的引用,并在完成后使其无效。
根据更新的问题详细信息,使用计时器并使其无效正成为一种更优选的方法,取消执行选择器是可行的,但它不像计时器路由那样清晰。我将显示执行选择器路由的代码:
- (void)startEverything
{
[self performSelector:@selector(showAlert) withObject:nil afterDelay:10];
}
- (void)handleButtonTap:(id)sender
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showAlert) object:nil];
}
- (void)showAlert
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlertView"
message:[NSString stringWithFormat:@"%d", hi]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
使用计时器会有相同的方法结构,但需要@property
来存储计时器而不是cancelPreviousPerformRequestsWithTarget...
,而是[self.timer invalidate]; self.timer = nil;
。
答案 1 :(得分:0)
我个人只会使用performSelector:withObject:afterDelay:
它看起来像这样:
// Action on button press
- (IBAction)myActionButtonPress:(id)sender {
// setup the selector to fire in 10 seconds
[self performSelector:@selector(showAlert) withObject:nil afterDelay:10.0];
}
// the selector to be called
- (void)showAlert {
// display alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlertView"
message:@"This alert displayed 10 seconds after button press"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
这将在10秒后激活你的动作方法。
答案 2 :(得分:0)
试试这个:
-(IBAction)btnDoneClick:(id)sender {
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(buttonactionalert) userInfo:nil repeats:NO];
}
-(void) buttonactionalert {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlertView"
message:[NSString stringWithFormat:@"%d", hi]
delegate:hi
cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
[alert show];
}