-1

我的计时器没有重复运行有问题。我仍然是 iOS 编码的新手,但从我在这个网站上收集的内容和对其他问题的回答来看,它应该可以工作。基本上,计时器应该在按下 timerStart 按钮时开始更新,并在按下 timerStop 按钮时停止。

下面是示例代码 .h 文件

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

    @interface PGSecondViewController : UIViewController <CLLocationManagerDelegate>

    {
    NSTimer *Timer;
    IBOutlet UILabel *displayTimer;
    int ticks;

    }

    @property (nonatomic, retain) IBOutlet UILabel *displayTimer;

    -(IBAction)timerStart:(id)sender;
    -(IBAction)timerStop:(id)sender;
    -(void)updateTimer:(NSTimer *)theTimer;

    @end

这是.m文件

#import "PGSecondViewController.h"

@interface PGSecondViewController ()

@end

@implementation PGSecondViewController

@synthesize displayTimer;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    UITabBarItem *tbi = [self tabBarItem];
    [tbi setTitle:@"Start"];

    // Custom initialization
}
return self;
}


- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[displayTimer setText:@"00:00:00"];

}

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}  

-(IBAction)timerStart:(id)sender;
{
Timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self     selector:@selector(updateTimer:) userInfo:nil repeats:YES];


}
-(IBAction)timerStop:(id)sender;
{
[Timer invalidate];
Timer = nil;
}

-(void)updateTimer:(NSTimer *)theTimer
{
if (ticks == nil)
{
    ticks = 0;
}
else
{
    ticks = ticks + 1;
}
[displayTimer setText:[NSString stringWithFormat:@" %d ", ticks]];

}


@end

基本上我得到的是计时器开始一次并且 NSLabel 显示 0 但之后没有任何反应。我已经在安排计时器后使用 [[NSRunLoop currentRunLoop] addTimer:Timer forMode:NSDefaultRunLoopMode] 和 [[NSRunLoop currentRunLoop] run] 进行了尝试,但它没有帮助。

有任何想法吗??

4

1 回答 1

2

你的 if(ticks == nil) 坏了;ticks 是一个 int,而不是一个对象。它的初始值为 0。

我只是通过稍微更改该方法来修复,一切正常。

-(void)updateTimer:(NSTimer *)theTimer
{
    ticks++;
    [displayTimer setText:[NSString stringWithFormat:@" %d ", ticks]];
}
于 2013-01-15T20:59:56.080 回答