如何在Xcode中释放视图

时间:2012-02-13 18:10:06

标签: view xcode4.2 release nstimer

您好我有一个秒表视图,当用户点击后退按钮转到另一个视图时,秒表将停止。我有人告诉我那是因为它正在被释放。

我希望秒表继续运行。

那么如何取消释放或不允许它被释放?

这是我的代码。

·H

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;

的.m

- (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]; 
}

1 个答案:

答案 0 :(得分:0)

我会尝试一种不同的方法,而不是改变视图控制器的行为:

通过将计时器功能移动到单独的对象中,可以使计时器独立于视图控制器。这样,计时器对象具有与视图控制器对象不同的生命周期。例如,您可以在应用程序委托中创建(和释放)计时器对象,并创建对它的引用并在视图控制器中访问它。