简体   繁体   中英

What does this block syntax do?

I have this code which is part of a (pretty long) method signature:

[...]requestCreator:(NSURLSessionDataTask *(^)(void (^)(NSURLSessionDataTask *, NSError *)))creator {
//
};

I don't quite get the fact that no variable names are there in parameters and what appears to be a type cast before.

Can someone break down this syntax and explain what's the behavior here?

Take the original method parameter declaration:

(NSURLSessionDataTask *(^)(void (^)(NSURLSessionDataTask *, NSError *)))creator

The form of such a declaration is (type)identifier . So, the identifier is creator and the type is:

NSURLSessionDataTask *(^)(void (^)(NSURLSessionDataTask *, NSError *))

In a local variable declaration, that would look like this possibly more-familiar format, instead:

NSURLSessionDataTask *(^creator)(void (^)(NSURLSessionDataTask *, NSError *))

Let's rework that with some typedefs:

typedef void (^TaskErrorHandlerBlock)(NSURLSessionDataTask *, NSError *);
typedef NSURLSessionDataTask* (^TaskCreatorBlock)(TaskErrorHandlerBlock);
TaskCreatorBlock creator;

I've made up the names TaskErrorHandlerBlock and TaskCreatorBlock from my guess as to what they do. A TaskCreatorBlock is a block which returns an NSURLSessionDataTask* – it creates such a task object. It takes as input a TaskErrorHandlerBlock , which is presumably a block which is called if there's an error. It takes as parameters the task which encountered the error and the error itself.

它看起来像一个需要另一个获得url会话和错误的块的块。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM