Reputation: 360
I have a little trouble understanding how this works. I am currently working with a sync table which uses calls like the following:
-(void)addItem:(NSDictionary *)item completion:(CompletionBlock)completion{
[self.syncTable insert:item completion:^(NSDictionary *result, NSError *error) {
[self LogErrorIfNotNil:error];
}];
I understand how you can use a block as a parameter to execute some extra code within your function, for example with dispatch_async. but when it comes to this line
[self.syncTable insert:item completion:^(NSDictionary *result, NSError *error) {
result is here a dictionary including all extra columns that follows after "item" has been added to the table. Thinking about it,it seems that "result" is more like the resulting type of addItem: instead of being a parameter of the method (due to being the result of the executed method)
EDIT: Basically, I don't understand where the NSDictionary *result variable comes from. To me it seems it should be return type of addItem:item
Upvotes: 0
Views: 57
Reputation: 3146
Here is an explanation of how the above blocks work and in what order.
Completions aren't really return values, perhaps that is what is confusing you. A completion block is a way for you to send code to a method that can be run within the scope of that method.
So when you send a block to a method, this is a possible order of events...
- (void)addItem:(NSDictionary *)item completion:(CompletionBlock)completion {
NSLog(@"1");
[self.syncTable insert:item
completion:^(NSDictionary *result, NSError *error) {
NSLog(@"2");
}
];
NSLog(@"3");
}
// SyncTable.m?
- (void)insert:(NSDictionary *)item completion:(CompletionBlock)completion {
NSLog(@"4");
NSDictionary *result = ...; // Prepare the result dictionary to be used in the completion block.
NSError *error = nil
completion(result, &error);
}
The order of these logs will output is as follows...
1
3
4
2
Notice that 2
is not logged until the completion block is called in insert:completion:
? Does this clarify the use of parameters in a block?
Upvotes: 1