2014-06-07 70 views
1

我正在處理每次計數器倒數時都會從網站獲取數據的內容。問題是我希望計數器在用戶離開視圖時停止並且不要繼續檢索數據。我一直試圖加入這個,當離開視圖時停止NSTimer

[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]; 

回答

2

爲了做到這一點,你需要設置你的NSTimer@property

[_timername invalidate]; 
_timername = nil; 

viewWillDisappear:方法。

諸如此類,,

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

    [_timername invalidate]; 
    _timername = nil; 
} 
+0

感謝你的信息。我補充說,它在運行,但是當我離開視圖並返回時,我的計數器不會從10重新開始,它將從8重新開始。如果我離開並再次返回一次,計數器將從7等等。我的計數器代碼似乎有一個小故障。我希望這會重新啓動計數器,每次我離開,然後回去,但事實並非如此。有任何想法嗎? – user3717503

+0

爲什麼要寫一個屬性,如果你只是直接訪問iVar? –

0
-(void) viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     if ([timername isValid]) { 
      [timername invalidate]; 
      timername = nil; 
     } 
    }); 
}