Home

Objective-C Quick tip: Assigning a block to a variable

learn-64058_640

A quick Objective-C tip on  Assigning a block to a variable. An interesting way to declare an object, such as a UIButton, for instance would be to create a block, and have that equal the containing variable. For instance:

self.contentButton = ({
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectNull];
        [button addTarget:self action:@selector(showViewController) forControlEvents:UIControlEventTouchUpInside];
        button;
    });

 

You are assigning an instance contentButton UIButton to what you get finalised/returned in the subsequent block. So, within the block, you create a UIButton, add some attributes/properties, which in this case is a target to the button. You have the last line be that in-line button, which is it's way of returning the same type as what your containing instance variable self.contentButton is.

Hopefully I can teach myself to remember this great convenience concept, bundles things up neater for sure.