8

我試圖從一個標籤,使用庫中獲取ID。在後臺做一些工作,並返回結果

我想出了以下內容。查找標籤的循環在後臺完成,我在tagAsString中得到了正確的結果。

-(void) readTag { 
    NSLog(@"readTag"); 
    unsigned char * tagUID = (unsigned char *) malloc(M1K_UID_SIZE * sizeof(char)); 
    //work to do in the background 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     ERR ret; 
     while ((ret = scanner->IsTagAvailable(tagUID)) != ERR_TAG_AVAILABLE) { 
      NSLog(@"ret: %d", ret); 
     } 


     //main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      if(ret == ERR_TAG_AVAILABLE) { 
       NSLog(@"tag available"); 
       NSString *tagAsString = [[[NSString alloc] initWithFormat:@"%x%x%x%x", tagUID[0],tagUID[1],tagUID[2],tagUID[3]] retain]; 

      } 
     }); 
    }); 
} 

我希望能夠返回值,這樣我就能夠調用:

NSString * myTag = [self readTag]; 

這可能嗎? 感謝您的幫助,邁克爾

回答

12

這是可能的,但是從該函數返回字符串的問題是,它將需要阻止你的調用線程,同時你在後臺執行工作 - 從而失去後臺線程。 (dispatch_sync是你用來做的 - 但我不會推薦它)。

使用塊時,最好重構程序以更好地適應異步範例。工作完成後,應通過向其發送消息並通知結果通知等待結果的任何內容。在你的例子中,你會把它放在主隊列中的代碼塊中。

@interface TagManager 
- (void)fetchTag; 
- (void)tagFetched:(NSString *)tag; 
@end 

@implementation TagManager 
- (void)fetchTag { 
    // The following method does all its work in the background 
    [someObj readTagWithObserver:self]; 
    // return now and at some point someObj will call tagFetched to let us know the work is complete 
} 

- (void)tagFetched:(NSString *)tag { 
    // The tag read has finished and we can now continue 
} 
@end 

然後你readTag功能將被修改爲這樣:

- (void)readTagWithObserver:(id)observer { 
    ... 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     ... 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      if (tag is ok) { 
       [observer tagFetched:tag]; 
      } 
     }); 
    });       
} 

主要的想法是,你需要了分裂的處理分爲兩個階段

  1. 要求,一些工作完成(在我的示例中爲fetchTag)
  2. 處理結果(tagFetched:在我的示例中)
+0

謝謝你的回答。你的意思是使用NSNotification來通知還是有其他方法? – Themikebe 2011-05-17 14:51:03

+0

NSNotification是一種可能的方式,但是在這個例子中我只是使用消息傳遞(方法調用)。我將用一個例子編輯我的答案 – jjwchoy 2011-05-17 14:56:50