Multithreading 在后台做一些工作并返回结果

Multithreading 在后台做一些工作并返回结果,multithreading,background,return-value,objective-c-blocks,Multithreading,Background,Return Value,Objective C Blocks,我正在尝试使用库从标记中获取ID 我得出了以下结论。查找标记的循环是在后台完成的,我在TagaString中得到了正确的结果 -(void) readTag { NSLog(@"readTag"); unsigned char * tagUID = (unsigned char *) malloc(M1K_UID_SIZE * sizeof(char)); //work to do in the background dispatch_async( dispat

我正在尝试使用库从标记中获取ID

我得出了以下结论。查找标记的循环是在后台完成的,我在TagaString中得到了正确的结果

-(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];
可能吗?
感谢您的帮助,Michael

这是可能的,但是从该函数返回字符串的问题是,当您在后台执行工作时,它需要挂起调用线程,从而失去后台线程的好处。(您可以使用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];
           }
        });
    });                          
}
主要思想是您需要将处理过程分为两个阶段

  • 请求完成一些工作(在我的示例中为fetchTag)
  • 完成后处理结果(tagFetched:在我的示例中)

  • 谢谢你的回答。您的意思是使用NSNotification来通知还是有其他方法?NSNotification是一种可能的方法,但是在本例中,我只使用消息传递(方法调用)。我将用一个例子来编辑我的答案