如何返回__block变量?

时间:2013-11-13 08:07:46

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

我有以下代码:

- (Transporter *) getTransporter:(NSNumber *)transporterId
{
    for(Transporter *transporter in transporters)
    {
         if([transporter.transporterId isEqualToNumber:transporterId])
         {
             return transporter;
         }
    }
    __block Transporter *transporter;

    [self requestTransporter:transporterId completion:^(NSObject *entity) {
        transporter = (Transporter* )entity;
     }];

    return transporter;
}

我的问题是:__block Tranporter是如何工作的? iOS等待变量得到值吗?或者我有一个零值,后来是一个对象?

块方法是否适用于具有返回值的方法?

2 个答案:

答案 0 :(得分:3)

__block关键字允许您修改(读写访问)变量,此处为transporter。 如果你的方法requestTransporter同步,他将被执行并将在它的调用结束之前执行他的完成块。 您还可以使用以下模式。

- (void) getTransporter:(NSNumber *)transporterId withCompletionBlock:(void(^)(Transporter*))completionBlock
{
    if(!completionBlock)
      return; //Avoid crashs.

    for(Transporter *transporter in transporters)
    {
         if([transporter.transporterId isEqualToNumber:transporterId])
         {
             completionBlock(transporter);
             return;
         }
    }

    [self requestTransporter:transporterId completion:^(NSObject *entity) {
        completionBlock((Transporter* )entity);
     }];
}

并像这样使用它:

// transporterId is an NSNumber containing your transporter id.
[self getTransporter:transporterId withCompletionBlock:^(Transporter *transporter) {
    // Execute your code using transporter object here.
}];

答案 1 :(得分:1)

只要块是异步的,就会立即返回传输器,没有分配的实体。

使用完成处理程序,如下所示:

- (void) requestTransporter:(NSNumber *)transporterId withCompletionBlock:(void(^)(Transporter))completionBlock
{
  for(Transporter *transporter in transporters)
   {
     if([transporter.transporterId isEqualToNumber:transporterId])
     {
         completionBlock(transporter);
     }
   }
__block Transporter *transporter;

[self requestTransporter:transporterId completion:^(NSObject *entity) {
    transporter = (Transporter* )entity;
    completionBlock(transporter);
 }];

}