Ios 离开视图时停止NSTimer

Ios 离开视图时停止NSTimer,ios,xcode,nstimer,Ios,Xcode,Nstimer,我正在做一件事,每次计数器倒计时都会从网站上获取数据。问题是,我希望当用户离开视图而不继续检索数据时,计数器停止。我一直想把这个加进去 [timername invalidate]; 无济于事。有人能告诉我需要做什么,以便在视图离开时计时器停止,在有人返回视图时从新计时器重新启动吗 谢谢 #import "Price.h" @interface Price () @property (strong, nonatomic) IBOutlet UILabel *priceLabel; @prop

我正在做一件事,每次计数器倒计时都会从网站上获取数据。问题是,我希望当用户离开视图而不继续检索数据时,计数器停止。我一直想把这个加进去

[timername invalidate];
无济于事。有人能告诉我需要做什么,以便在视图离开时计时器停止,在有人返回视图时从新计时器重新启动吗

谢谢

#import "Price.h"

@interface Price ()
@property (strong, nonatomic) IBOutlet UILabel *priceLabel;
@property (strong, nonatomic) IBOutlet UILabel *countdownLabel;


@end

@implementation Price
int counter;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    counter = 10;

    [NSTimer scheduledTimerWithTimeInterval:1.0 target:(self) selector:@selector(countdown) userInfo:nil repeats:YES];
}



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


-(void)getPrice{
    NSURL *url = [NSURL URLWithString:@"myURL"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error ==nil){
             NSDictionary *spotPrice = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]
             ;
             self.priceLabel.text = [[[spotPrice objectForKey:@"amount"] stringByAppendingString:@" "]stringByAppendingString:[spotPrice objectForKey:@"currency"]];
         }

     }];
}

-(void)countdown{
    counter--;
    self.countdownLabel.text = [NSString stringWithFormat:@"%d", counter];
    if (counter == 0){
        counter = 15;
        [self getPrice];

要执行此操作,您需要设置
NSTimer的
@属性
,然后写入

[_timername invalidate];
 _timername = nil;
视图将消失:
方法

比如,

- (void)viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];

    [_timername invalidate];
    _timername = nil;
}

谢谢你的信息。我在中添加了它,但是当我离开视图返回时,计数器不会从10重新启动。它将从8点重新开始。如果我离开后再回去一次,计数器将从7重新开始,依此类推。我的计数器代码似乎有个小故障。我希望每次我离开和回去的时候都能重新启动计数器,但事实并非如此。有什么想法吗?如果你想直接访问iVar,为什么要写一个属性?
-(void) viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([timername isValid]) {
            [timername invalidate];
            timername = nil;
        }
    });
}