iphone - 如何在同步函数调用中处理异步回调?

标签 iphone objective-c ios callback objective-c-blocks

我有一个在回调中异步返回对象(例如 UserProfile)的方法。

基于此 UserProfile 对象,一些代码计算 UITableViewCell 是否可编辑:

我创建了以下代码,但不幸的是它不起作用。

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{        
    Entry *entry = [[self.feed entries] objectAtIndex:[indexPath row]];
    typedef BOOL (^BOOLBlock)(id);

    BOOLBlock bar = ^BOOL (id p) {
        if (p) {
            UserProfile *user = (UserProfile *) p;
            NSEnumerator *e = [[entry authors] objectEnumerator];
            id object;
            while (object = [e nextObject]) {
                if ([[object name] isEqualToString:[[[user authors] objectAtIndex:0] name]])
                    return TRUE;
            }
            return FALSE;
        } 
        else {
            return FALSE;
        }
    };

    [[APPContentManager classInstance] userProfile:bar];    
}

在最后一行,它显示发送不兼容的 block 指针类型

'__strong BOOLBlock' (aka 'BOOL (^__strong)(__strong id)') to parameter of type 'void (^)(UserProfile *__strong)'

APPContentManager.h

-(void)userProfile:(void (^)(UserProfile *user))callback;

最佳答案

-userProfile: 方法不需要您的 BOOLBlock 类型 - 它不负责返回任何内容。您想在此处使用信号量,但您应该记住 Till 关于 -tableView:canEditRowAtIndexPath: 的预期同步性的评论 - 如果您的 userProfile: 方法需要一段时间,那么您绝对应该预先缓存此可编辑信息。

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {        
    Entry *entry = [[self.feed entries] objectAtIndex:[indexPath row]];
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    __block BOOL foundAuthor = NO;

    [[APPContentManager classInstance] userProfile:^(UserProfile *user) {
        NSEnumerator *e = [[entry authors] objectEnumerator];
        id object;
        while (object = [e nextObject]) {
            if ([[object name] isEqualToString:[[[user authors] objectAtIndex:0] name]]) {
                foundAuthor = YES;
                break;
            }
        }
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    dispatch_release(sema);

    return foundAuthor;
}

关于iphone - 如何在同步函数调用中处理异步回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032750/

相关文章:

iphone - iCloud - 移动文件完成

ios - 以编程方式将 UIButtons 添加到 UICollectionView 单元格的 uiimage

objective-c - iOS 方向 : Tried this and tried that

ios - 获取 iPod 播放器项目的 iTunes ID

c++ - XCode 调试器 lldb 在没有错误输出的情况下中断,但程序运行正常

ios - 将图像和文本绘制成单个图像

ios - UIActivityIndi​​cator 显示一瞬间

javascript - iOS自动悬停修复?

iphone - 通过 wifi 在 2 部 iPhone 之间传输文件?

objective-c - 如何向字符串添加度数符号?