我是iPhone应用程序的新手。我想在按下按钮时每2秒显示一次消息 为此,我使用此代码。
此代码只能工作一次。这意味着只召唤一次。你能帮我解决这个问题。
-(IBAction)fortunecookieAction:(id)sender
{
[self performSelector:@selector(showfortune) withObject:nil afterDelay:2.0];
}
-(void)showfortune
{
int number=arc4random()%5;
switch (number) {
case 0:
fortunelabel.text=@"A holiday takes you back to the summer of '69";
break;
case 1:
fortunelabel.text=@"A meal turns erotic muffin";
break;
case 2:
fortunelabel.text=@"A massage brings";
break;
case 3:
fortunelabel.text=@"A letter in the pa special delivery";
break;
case 4:
fortunelabel.text=@"A spillage tuoo";
break;
default:
break;
}
}
答案 0 :(得分:0)
如果你想每隔2秒调用一次该功能,请使用NSTimer
您需要scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
来创建计划的计时器
答案 1 :(得分:0)
您最好的选择可能是使用NSTimer
。你可以设置一个非常容易每两秒调用一次动作方法:
在您的界面(MyViewController.h
)中,声明NSTimer属性:
@interface MyViewController : UIViewController
@property (nonatomic, retain) NSTimer *myTimer;
@end
然后在您的实施中:
@synthesize myTimer;
- (void)viewDidLoad
{
[super viewDidLoad];
NSTimer *newTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(repeatingTimerFired:) userInfo:nil repeats:YES];
self.myTimer = newTimer;
[newTimer release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
if ([myTimer isValid]) {
[myTimer invalidate];
}
}
- (void)dealloc
{
[myTimer release], myTimer = nil;
[super dealloc];
}
- (void)repeatingTimerFired:(NSTimer *)sender
{
int number=arc4random()%5;
switch (number) {
case 0:
fortunelabel.text=@"A holiday takes you back to the summer of '69";
break;
case 1:
fortunelabel.text=@"A meal turns erotic muffin";
break;
case 2:
fortunelabel.text=@"A massage brings d";
break;
case 3:
fortunelabel.text=@"A letter in the pa special delivery";
break;
case 4:
fortunelabel.text=@"A spillage tuoo";
break;
default:
break;
}
如果您希望此计时器在用户按下按钮后开始显示消息,只需将计时器创建移动到按钮操作方法。