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

相关问题