2011-09-15 80 views
0

我是新的iPhone應用程序。我想在按下按鈕時每2秒顯示一個消息 爲此,我正在使用此代碼。有關performSelector

此代碼僅工作一次。這意味着只打一次電話。你能幫我解決這個問題嗎?

-(IBAction)fortunecookieAction:(id)sender 
{ 
    [self performSelector:@selector(showfortune) withObject:nil afterDelay:2.0]; 
} 

-(void)showfortune 
{ 
    int number=arc4random()%5; 
    switch (number) { 
     case 0: 
      [email protected]"A holiday takes you back to the summer of '69"; 
      break; 
     case 1: 
      [email protected]"A meal turns erotic muffin"; 
      break; 
     case 2: 
      [email protected]"A massage brings"; 
      break; 
     case 3: 
      [email protected]"A letter in the pa special delivery"; 
      break; 
     case 4: 
      [email protected]"A spillage tuoo"; 
      break; 

     default: 
      break; 
    } 
} 
+0

我不明白這個問題。輕按按鈕後,是否要重複更改文字? –

回答

0

如果您想每2秒調用一次該功能,請使用NSTimer
您將需要scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:創建計劃的計時器

0

您最好的選擇是使用NSTimer。你可以設置一個真正輕鬆地調用action方法每兩秒鐘:

在你的界面(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: 
      [email protected]"A holiday takes you back to the summer of '69"; 
      break; 
     case 1: 
      [email protected]"A meal turns erotic muffin"; 
      break; 
     case 2: 
      [email protected]"A massage brings d"; 
      break; 
     case 3: 
      [email protected]"A letter in the pa special delivery"; 
      break; 
     case 4: 
      [email protected]"A spillage tuoo"; 
      break; 

     default: 
      break; 
} 

如果您希望此計時器在用戶按下按鈕後開始顯示消息,只需將計時器創建移動到按鈕操作方法。

+0

我這樣做,但如何阻止這個失效不起作用 – sai

+0

@sai:如果你想在稍後時間使它失效,那麼你將需要使用聲明的屬性來保持對定時器的引用。確保它在'viewDidUnload'內部是無效的,並且釋放位於'dealloc'中,否則計時器(和您的視圖控制器,作爲目標)將不會從運行循環中移除。 – Stuart

+0

@sai:我編輯了我的答案以包含如何做到這一點的詳細信息(請參閱示例代碼)。 – Stuart