开发者

Store time from NSTimer for next view (HELP!)

I'm becomming desperate. I've got a NSTimer in my second ViewController.

-(IBAction)start {
    myticker = [NSTimer scheduledTimerWithTimeInterval:0.01 
                                                target:self 
                                              selector:@selector(showActivity) 
                                              userInfo:nil 
                                               repeats:YES];
}

-(IBAction)stop {
    [myticker invalidate];
}

-(void)showActivity {
float currentTime = [time.text floatValue];
newTime = currentTime + 0.01;
time.text = [NSString stringWithFormat:@"%.2f", newTime];        
}

newTime ist an instance variable (float) and time is the label where the time is shown.

Before calling the third ViewController, I stored the time this:

-(IBAction)right {

[self stop];

ThirdViewController *screen = [[ThirdViewController alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
screen.timelabel.text = [NSString stringWithFormat: @"%.2f", newTime];
[self presentModalViewController:screen animated:YES];
[screen release];
}

I stopped the timer and gave the time to the instance variable timelabel (UILabel). In the third ViewController I created the same NSTimer with the same methods. But when I open the th开发者_如何学编程ird View Controller the timer starts from 0 again.

What's wrong about my code?


My third ViewController:

-(IBAction)start {

    myticker = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];

}


-(IBAction)stop {

    [myticker invalidate];

}

-(void)showActivity {

    float currentTime = [timelabel.text floatValue];
    float newTime = currentTime + 0.01;
    timelabel.text = [NSString stringWithFormat:@"%.2f", newTime];        
}


First of all, please move you third controller code to the question.

You are not retaining myticker. I'm surprised that it works at all.

It is a bad idea to store float data in text field. It would be better to use float property for that:

@interface MyController : UIViewController
{
  float currentTime;
  ...
}

@property (nonatomic, assign) float currentTime;
...

@end

@implementation MyController

@syntesize currentTime;

-(IBAction)start {
    self.myticker = [NSTimer scheduledTimerWithTimeInterval:0.01 
                                                target:self 
                                              selector:@selector(showActivity) 
                                              userInfo:nil 
                                               repeats:YES];
}

-(void)showActivity {
  currentTime += 0.01;
  time.text = [NSString stringWithFormat:@"%.2f", currentTime];        
}
...

@end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜