John Smith
John Smith

Reputation: 1876

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?

Upvotes: 0

Views: 128

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90571

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.

Upvotes: 4

0xFADE
0xFADE

Reputation: 832

It looks like a block that takes another block that gets a url session and error.

Upvotes: 2

Related Questions