Search code examples
iosobjective-cblock

Method with completion handler


I've created a method in a class:

- (void)getTableData:(NSString *)URL withCompletionHandler:(void (^)(NSString *))handler{

__block NSDictionary *JSON;
[manager POST:urlString parameters:jsonDict success:^(AFHTTPRequestOperation *operation, id responseObject){

    JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
    handler(JSON);
}
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"error %@",error);
          // handle failure
      }];
}

and call it in another class by

[ObjOfSecondClass getTableData:BILL withCompletionHandler:^(NSString* returnString)handler{
    }];

It shows Expected expression error at handler.


Solution

  • It's an expression error because you are using it in wrong way.

    Try this one in viewDidLoad

    [ObjOfSecondClass getTableData:BILL withCompletionHandler:^(NSString* returnString){
    }];
    

    handler is used is block implementation to return value from where they are called.

    Note - replace string to dictionary in block definition because you are getting dictionary from API not string.

    Learn block syntax