2012-07-23 47 views
1

修改的UILabel我有以下定时器:iPhone/Objective-C的:如何从计时器

uploadGPS_timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(uploadGPS_tick:) userInfo:nil repeats:YES]; 
[self uploadGPS_tick:nil]; 

这里是回调:uploadGPS_tick():

-(void)uploadGPS_tick:(NSTimer*)timer{ 
    if(!lat || !lng){ 
     //do nothing 
    }else{ 
     NSString *urlStr=[[NSString alloc] initWithFormat:@"http://www.example.com/ajax/updateCoords.php"]; 
     NSURL *url=[NSURL URLWithString:urlStr]; 

     __block ASIFormDataRequest *request=[[ASIFormDataRequest alloc ]initWithURL:url]; 
     [request setPostValue:lat forKey:@"lat"]; 
     [request setPostValue:lng forKey:@"lng"]; 
     NSLog(@"EOH: %@",lat); 
     [request setDelegate:self]; 
     [request setCompletionBlock:^{ 
      NSString *response=[request responseString]; 
      NSLog(@"%@",response); 

      if([response isEqualToString:@"LO"]){ 
       [self.navigationItem setBackBarButtonItem:nil]; 
       DriverLogin *x= [[DriverLogin alloc] initWithNibName:nil bundle:nil]; 
       [[self navigationController]pushViewController:x animated:NO]; 
      } 

      SBJsonParser *parser=[[SBJsonParser alloc]init]; 
      NSMutableDictionary *obj=[[NSMutableDictionary alloc]init ]; 
      obj=[[parser objectWithString:[request responseString] error:nil]retain]; 

      credits.text=[[obj objectForKey:@"credits"] stringValue]; //this won't show... 
      creditsUsed.text=[[obj objectForKey:@"creditsUsed"] stringValue]; //this won't show... 
      NSInteger timeLeftSecs=[[obj objectForKey:@"creditTimeLeft"] intValue]; 
      NSInteger timeLeftMins=(int)(timeLeftSecs/60); 
      creditTimeLeft.text=[[NSString alloc]initWithFormat:@"%d",timeLeftMins]; //this won't show... 

      NSLog(@"xxx:%@",obj); 

     }]; 
     [request setFailedBlock:^{ 
      NSError *error =[request error]; 
      NSLog(@"%@",error); 
      //do nothing 
     }]; 
     [request startAsynchronous]; 
    } 
} 

正如你所看到的,每五秒钟,一个JSON对象从服务器发送。然后分析此JSON对象,并根据此JSON数据设置三个UILabels。

我遇到的麻烦是UILabels没有得到他们的文本集!尽管我可以在调试器中清楚地看到NSLog(@"xxx:%@",obj);。 UILabel在.xib中正确连接。

任何帮助非常感谢。

+1

UI元素只能从主循环更新。你确定你正在UI更新代码的主循环上运行吗? – 2012-07-23 08:43:41

+0

嗯。我不知道。如何检查这个?非常感谢, – Eamorr 2012-07-23 08:44:26

+1

'ASIHTTPRequest'总是在主线程上回调。 – Lvsti 2012-07-23 08:48:16

回答

2

你应该从主线程做到这一点。将标签文本分配替换为以下代码:

dispatch_async(dispatch_get_main_queue(), ^{ 
    creditTimeLeft.text=[NSString stringWithFormat:@"%d",timeLeftMins]; 

});