Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void(^)(NSData*) what does it mean?

Hi I am using this library and I found the function:

- (void) queueRequest:(NSString*)urlPath completion:(void(^)(NSData*))completionWithDownloadedData;

I try to pass a simple NSData *data; and it throw an error, what really mean (void(^)(NSData*))? Is the first time that I see it.

Thanks a lot.

like image 515
ƒernando Valle Avatar asked Dec 05 '22 12:12

ƒernando Valle


2 Answers

(void(^)(NSData*)) declares a code block. You can call your function this way.

[obj queueRequest:urlPath completion:^(NSData* data){
            /* some code */
        }];

data is a parameter to your block, which you can work with. The block will be called when the queueRequest will finish, asynchronously.

like image 89
tomahh Avatar answered Dec 25 '22 08:12

tomahh


The interface is asynchronous, meaning that the data will only be available sometime later. This means that the method can’t simply return the NSData* (without blocking for all the time, which is impractical). The problem is nowadays often solved with blocks, and the completion argument here is a block that takes an NSData* argument and returns void. This is how you call such a method:

[foo queueRequest:path completion:^(NSData *receivedData) {
    NSLog(@"Received data: %@", receivedData);
}];

The call will return immediately and the block will be executed sometime later, when the data is available.

like image 33
zoul Avatar answered Dec 25 '22 09:12

zoul