Here’s some code that takes a block called success.


   AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        
        // city
        NSString *city = [JSON valueForKeyPath:@"location.city"];
        NSString *currentTemp = [JSON valueForKeyPath:@"current_observation.temp_c"];
        
        // create a weather object
        Weather *weather = [[Weather alloc] init];
        weather.city = city;
        weather.currentTemperature = [currentTemp intValue];

        // notify!
        NSDictionary *dictionaryWithWeather = 
        [NSDictionary dictionaryWithObject:weather forKey:WEATHER_KEY];
        [[NSNotificationCenter defaultCenter] postNotificationName:WEATHER_KEY 
object:self userInfo:dictionaryWithWeather]; 
        
    } ...

Cool. But what if I want to pull out that ‘success’ code out into a variable and pass it to the calling method. Here’s what it looks like.

First define a typedef for the block:

typedef void (^success)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON);

You can figure out the typedef method signature by looking at the underlying code, and then just sticking the word typdef in front of it. Note ‘success’ is the name of typdef here.

Then define a variable for the block:

    success requestSuccess;

Nothing magical. But I want you to see what assigning a variable to a block looks like. It looks like any other variable assignment.

Then instantiate your method and define the contents of the block.

    requestSuccess = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        // city
        NSString *city = [JSON valueForKeyPath:@"location.city"];
        NSString *currentTemp = [JSON valueForKeyPath:@"current_observation.temp_c"];
        
        // create a weather object
        Weather *weather = [[Weather alloc] init];
        weather.city = city;
        weather.currentTemperature = [currentTemp intValue];

        // notify!
        NSDictionary *dictionaryWithWeather = 
        [NSDictionary dictionaryWithObject:weather forKey:WEATHER_KEY];
        [[NSNotificationCenter defaultCenter] postNotificationName:WEATHER_KEY 
object:self userInfo:dictionaryWithWeather];        
    };

Then replace the code you pulled out with the call to the block variable:

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        
        requestSuccess(request, response, JSON);
        
    } 

Voila! Cleaner more readable code.

Advertisements