2

我有以下代码:

- (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 会等到变量获得值吗?还是我有一个 nil 值,然后是一个对象?

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

4

2 回答 2

3

__block 关键字允许您修改(读写访问)变量,此处为传输器。如果您的方法 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.
}];
于 2013-11-13T11:02:59.457 回答
1

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

像这样使用完成处理程序:

- (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);
 }];

}
于 2013-11-13T08:36:30.153 回答