dispatch_async返回方法目标c

San*_*ram 6 objective-c grand-central-dispatch

我一直在尝试dispatch_async在返回结果的方法中使用.但是,我观察到该方法在执行dispatch_async块之前返回.由于这个原因,我没有得到我期望的结果.这是一些演示我的问题的代码.

-(BOOL) isContactExists {
    BOOL isContactExistsInXYZ = YES;
    UserId *userId = contact.userId;
    dispatch_async(dispatch_get_main_queue(), ^
    {
        iOSContact *contact = [iOSContact contactForUserId:userId];
        if (nil == contact)
        {
          isContactExistsInXYZ = NO;
        }
    });    

    return isContactExistsInXYZ;
}
Run Code Online (Sandbox Code Playgroud)

isContactExists其他地方调用此方法,并根据该方法的响应,我必须做一些事情.但每一次,价值isContactExistsInXYZ都不是我所期望的.任何人都可以解释dispatch_async在这种情况下如何处理?

谢谢.

Pet*_*lom 12

如果你去块路线你的方法需要看起来像这样.

- (void)isContactExistsWithCompletionHandler:(void(^)(BOOL exists)) completion 
{
    dispatch_async(dispatch_get_main_queue(), ^
    {
        BOOL isContactExistsInXYZ = YES;
        UserId *userId = contact.userId;
        iOSContact *contact = [iOSContact contactForUserId:userId];
        if (nil == contact)
        {
          isContactExistsInXYZ = NO;
        }
        completion(isContactExistsInXYZ);
    });
}
Run Code Online (Sandbox Code Playgroud)

而你在哪里称它为这样的东西.

[someObject isContactExistsWithCompletionHandler:^(BOOL exists) {
    // do something with your BOOL
}];
Run Code Online (Sandbox Code Playgroud)

您还应该考虑将重型操作放在除主要操作之外的其他操作中.像这样.

- (void)isContactExistsWithCompletionHandler:(void(^)(BOOL exists)) completion 
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL);
    dispatch_async(queue, ^
    {
        BOOL isContactExistsInXYZ = YES;
        UserId *userId = contact.userId;
        iOSContact *contact = [iOSContact contactForUserId:userId];
        if (nil == contact)
        {
          isContactExistsInXYZ = NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^
        {
            completion(isContactExistsInXYZ);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)


Wai*_*ain 6

你需要尊重你想要做的事情是异步并接受它.这意味着不使用返回值.相反,您可以编写您的方法以将回调块作为参数.然后,当您的异步检查完成后,您可以使用结果调用该块.


所以你的方法签名将成为:

- (void)checkIfContactExistsWithCompletion:(ContactExistsBlock)completion {
Run Code Online (Sandbox Code Playgroud)

ContactExistsBlock块定义在哪里没有返回,可能是单个BOOL参数.

typedef void (^ContactExistsBlock) (BOOL exists);
Run Code Online (Sandbox Code Playgroud)