需要有关理解typedef和块的帮助

S.J*_*S.J 2 objective-c ios objective-c-blocks

typedef void (^RequestProductsCompletionHandler)(BOOL success, NSArray * products);
Run Code Online (Sandbox Code Playgroud)

我很难理解这行代码在.h文件中的作用.

请详细解释

  1. 的typedef.
  2. 无效(我知道什么是无效的,但这里的目的是什么?).
  3. (^ RequestProductsCompletionHandler)(BOOL成功,NSArray*产品);
  4. 怎么称呼它?

Vla*_*mir 9

这是objective-c 类型的定义,其名称带有RequestProductsCompletionHandler2个参数(BOOL和NSArray),并且没有返回值.您可以像调用c函数一样调用它,例如:

RequestProductsCompletionHandler handler = ^(BOOL success, NSArray * products){
    if (success){
       // Process results
    }
    else{
       // Handle error
    }
}
...
handler(YES, array);
Run Code Online (Sandbox Code Playgroud)


Rob*_*Rob 7

弗拉基米尔描述得很好.它定义了一个变量类型,它将表示将传递两个参数的,一个布尔值success和一个数组products,但块本身返回void.虽然您不需要使用它typedef,但它使方法声明更加优雅(并避免您必须使用块变量的复杂语法).

为了给你一个实际的例子,可以从块类型的名称及其参数推断出这定义了一个完成块(例如,当一些异步操作(如慢速网络请求)完成时要执行的代码块).请参阅使用块作为方法参数.

例如,假设您有一些InventoryManager类可以从中请求产品信息,使用以下定义的接口的方法,使用typedef:

- (void)requestProductsWithName:(NSString *)name completion:(RequestProductsCompletionHandler)completion;
Run Code Online (Sandbox Code Playgroud)

你可以使用这样的方法:

[inventoryManager requestProductsWithName:name completion:^(BOOL success, NSArray * products) {

    // when the request completes asynchronously (likely taking a bit of time), this is
    // how we want to handle the response when it eventually comes in.

    for (Product *product in products) {
        NSLog(@"name = %@; qty = %@", product.name, product.quantity);
    }
}];

// but this method carries on here while requestProductsWithName runs asynchronously
Run Code Online (Sandbox Code Playgroud)

而且,如果你看一下它的实现requestProductsWithName,可以想象看起来像:

- (void)requestProductsWithName:(NSString *)name completion:(RequestProductsCompletionHandler)completion
{
    // initiate some asynchronous request, e.g.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // now do some time consuming network request to get the products here

        // when all done, we'll dispatch this back to the caller

        dispatch_async(dispatch_get_main_queue(), {
            if (products)
                completion(YES, products); // success = YES, and return the array of products
            else
                completion(NO, nil);       // success = NO, but no products to pass back
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

显然,这不太可能正是您的特定完成处理程序块正在做的事情,但希望它说明了这个概念.