Search code examples
objective-ccxcodeblock

Objective C: Anonymous Blocks, Why and When?


Recently, I was trying to debug some code and my mind was boggled as to what I was doing wrong. The simplified version of what my issue was is below:

for(int x = 0; x < [myArray count]; x++);
{
    //perform some action
}

The issue was that the action I wanted to perform would only happen one time. Of course, I eventually noticed the issue was that I was accidentally including an extra semicolon at the end of my for loop.

for(int x = 0; x < [myArray count]; x++);<---- Oops!
{
    //perform some action
}

But then I got to wondering... why did that code even sort of work? It turns out what was happening is that my for loop was executing, then the code below was being run as an "anonymous block".

  1. What is the point of an anonymous block in Objective C? When/where are they useful?

  2. Why would my code not generate some sort of warning in Xcode? I guess you can just throw any old section of code inside an extra pair of braces and you're suddenly executing it as anonymous block?


Solution

  • They can be used for scoping a variable. Although it's more of a typography thing, it can be handy when you need to customize a series of objects of the same type, allowing you to use the same variable repeatedly. Say for example that you're setting up some NSURLRequests:

    NSMutableArray *requests = [NSMutableArray array];
    {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        request.URL = [NSURL URLWithString:@"http://A"];
        request.HTTPMethod = @"GET";
        [requests addObject:request];
    }
    // ... etc
    {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        request.URL = [NSURL URLWithString:@"http://Z"];
        request.HTTPMethod = @"POST";
        [requests addObject:request];
    }