Xcode 计时秒表

Xcode 计时秒表,xcode,xcode4.2,nstimer,Xcode,Xcode4.2,Nstimer,我有一个秒表,在我的应用程序上运行良好,但当我点击后退按钮转到另一个视图时,它停止了。我希望秒表即使在用户查看其他页面时也能继续运行 我如何做到这一点 好,添加了代码 代码: h m 它停止了,因为当你将它从堆栈中弹出时,你正在释放它所在的视图。 您是否尝试过创建一个独立于视图处理计时器的秒表类 秒表停止,因为您正在释放控制它的视图。 您需要确保NSTimer未链接到任何视图。 也许您可以使用子视图或模态视图控制器(我认为这可能会起作用),以便在查看时不释放秒表 您还可以尝试通过变量将秒表信息发

我有一个秒表,在我的应用程序上运行良好,但当我点击后退按钮转到另一个视图时,它停止了。我希望秒表即使在用户查看其他页面时也能继续运行

我如何做到这一点

好,添加了代码

代码:

h

m


它停止了,因为当你将它从堆栈中弹出时,你正在释放它所在的视图。
您是否尝试过创建一个独立于视图处理计时器的秒表类

秒表停止,因为您正在释放控制它的视图。

您需要确保
NSTimer
未链接到任何视图。 也许您可以使用子视图或模态视图控制器(我认为这可能会起作用),以便在查看时不释放秒表

您还可以尝试通过变量将秒表信息发送到下一个视图,然后让另一个视图从那里接管秒表

当然还有其他方法


无论哪种方式,您都需要确保未释放
NSTimer

确切地说,如果您查看“ViewDidUnload”,则当视图被释放时,您将其设置为零,而当您转到另一个视图时,它会这样做

您可以尝试使用一个运行计时器的类,并将其发送到视图,这样即使显示计时器的视图不在内存中,它仍在运行


MVC风格

是的,其他人都这么说。
在ViewDidUnload上,它正在释放它。这意味着只要ViewController退出,它就基本上结束了操作。

我不知道问题是否已经解决,但仍然存在。
在App Delegate类中创建NSTimer的对象,然后实例化App Delegate的in.m文件中的计时器,这样您的NSTimer将保留在内存中。当您想要停止或暂停计时器时,您可以从任何视图控制器中使该对象无效。

哪个对象拥有NSTimer?确定当我从视图中删除它时,我收到很多错误。如果你知道我应该怎么做的话。我很感激。非常感谢。
UILabel *stopWatchLabel;

NSTimer *stopWatchTimer; // Store the timer that fires after a certain time
NSDate *startDate; // Stores the date of the click on the start button

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

- (IBAction)onStartPressed:(id)sender;
- (IBAction)onStopPressed:(id)sender;
- (void)viewDidUnload
{
[self setStopWatchLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
}

- (IBAction)onStartPressed:(id)sender {
startDate = [NSDate date];

// Create the stop watch timer that fires every 10 ms
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                                  target:self
                                                selector:@selector(updateTimer)
                                                userInfo:nil
                                                 repeats:YES];
}

- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer]; 
}