如何在局部变量中存储返回内容的块定义

时间:2014-06-26 08:06:46

标签: ios objective-c objective-c-blocks typedef

这对我来说有点奇怪,当我的block没有返回任何内容时,我可以在将它传递给消费者方法之前将其捕获到变量中。但是,一旦我向块typedef添加一个返回值,我就开始着眼了

场景1 :Block不会返回任何内容 //声明

typedef void (^MYConfigureBlock)(MYFeedCell *cell, NSIndexPath *indexPath);

//使用

  MYConfigureBlock block  = ^(MYFeedCell *cell, NSIndexPath *indexPath){
    [cell setActionDelegate:self];
    return nil;
};

MYFeedSource *fds = [[MYFeedSource alloc]initWithTableView:self.tableView
                                                    configurationBlock:block];
[fds setErrorMessage:@"No feeds yet. Is everyone even alive?"];
self.feedDataSource = fds;

除非我继续做下去,否则在上面的代码中每件事情都是完美的:

问题

typedef MYFeedCell* (^MYConfigureBlock)(MYFeedCell *cell, NSIndexPath *indexPath);

现在我该如何重写以下语句,以便没有错误。为什么这与返回类型不一样?

MYConfigureBlock block  = ^(MYFeedCell *cell, NSIndexPath *indexPath){
    [cell setActionDelegate:self];
    return nil;
};

错误是

  

将'MYFeedCell *'发送到不兼容类型'MYConfigureBlock'的参数(又名'MYFeedCell *(^)(MYFeedCell * __ strong,NSIndexPath * __ strong)')

使用块的代码

- (UITableViewCell*)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

            self.cellConfigureBlock(nil, indexPath);
}

2 个答案:

答案 0 :(得分:0)

您必须在块签名中包含块的返回类型,因为如果返回nil,编译器无法推断块的返回类型。试试这个:

MYConfigureBlock block = ^ MyFeedCell* (MYFeedCell *cell, NSIndexPath *indexPath){
    [cell setActionDelegate:self];
    return nil;
};

请注意,如果返回MyFeedCell对象,原始代码不会引发编译错误,因为编译器可以推断返回类型:

MYConfigureBlock block = ^(MYFeedCell *cell, NSIndexPath *indexPath){
    [cell setActionDelegate:self];
    return cell;
};

答案 1 :(得分:-1)

    /** PROBLEM is the nil return*/
    //  return nil;

    //SHOULD return a valid type,which is expected.----Here Cell object should return.
    return cell;