Xcode Balancing Brackets For Method Calls

This may well be my favourite and perhaps also the simplest Xcode completion trick I have come across. I may be the last person to discover it but just in case there is somebody else who is yet to find it…

I always find it a pain to think about how many opening brackets ("[") I need when starting to write Objective-C statements where you have several nested method calls. This means I often get to the end of the statement and find I have an extra opening bracket somewhere. Luckily Xcode will allow you to forget about the opening brackets and just type the closing brackets. The corresponding opening bracket is inserted for you by Xcode automatically. So for example assume I start typing the following sequence:

NSNumber *number10 = NSNumber alloc

At this point (with the cursor at the end of the line) typing a single closing bracket “]” causes Xcode to insert the corresponding opening bracket so you end up with this:

NSNumber *number10 = [NSNumber alloc]

If I then continue to type the rest of the statement I can repeat the same trick at this point:

NSNumber *number10 = [NSNumber alloc] initWithInteger:10 

Typing the final closing “]” again causes Xcode to insert the corresponding initial “[” to give us the following:

NSNumber *number10 = [[NSNumber alloc] initWithInteger:10]

Adding the final semicolon completes the statement:

NSNumber *number10 = [[NSNumber alloc] initWithInteger:10];

If for some strange reason you do not like this code completion you can disable it in Xcode preferences (look under Code completion in the Text Editing preferences pane).