我有一个在回调中异步返回对象(例如 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/