2012-05-04 74 views
0

我試圖做一個計時器,從30倒數到0,但這是我能想到使它工作的唯一方法,但它不起作用。任何人都知道我做錯了什麼?NSTimer/NSTimeInterval

.h文件中

@interface countDownAppViewController : UIViewController { 

UIButton *countDown; 
UILabel *displayThis; 
} 

@property (nonatomic, retain) IBOutlet UIButton *countDown; 
@property (nonatomic, retain) IBOutlet UILabel *displayThis; 

-(IBAction) theCount:(id) sender; 
-(IBAction) displayStuff:(id) sender; 

@end 

.m文件

@synthesize countDown; 
@synthesize displayThis; 

-(IBAction) theCount:(id) sender { 
[NSTimer scheduledTimerWithTimeInterval:1.0 
           target:self 
           selector:@selector(displayStuff:) 
           userInfo:nil 
           repeats:NO]; 

} 
int batman=30; 
-(void) viewDidLoad{ 

displayThis.text = [NSString stringWithFormat:@"%i",batman]; 
} 

-(IBAction) displayStuff:(id) sender { 
while (batman >= 0){ 
    batman--; 
    [NSTimer scheduledTimerWithTimeInterval:1.0 
            target:self 
            selector:@selector(displayStuff:) 
            userInfo:nil 
            repeats:NO]; 
displayThis.text = [NSString stringWithFormat:@"%i",batman]; 

} 
} 

回答

0

你試過寫它,它實際上應該已被寫入的方式嗎? repeats的論點完全是爲了這個目的。你可以寫這樣的方法:

@interface Whatever: UIViewController 
{ 
    NSTimer *timer; 
    int count; 
    int maxCount; 
} 

- (void)countDownFrom:(int)cnt; 

@end 

@implementation Whatever 

- (void)countDownFrom:(int)cnt 
{ 
    maxCount = cnt; 
    count = 0; 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
           target:self 
           selector:@selector(doCount) 
           userInfo:nil 
           repeats:YES]; 
} 

- (void)doCount 
{ 
    count++; 
    textField.text = [NSString stringWithFormat:@"Count: %d", count]; 
    if (count >= maxCount) 
    { 
     [timer invalidate]; 
    } 
} 

@end