wackytacky99 wackytacky99 -3 years ago 106
Objective-C Question

Using bracket notation in Objective-C

I have been learning Objective-C for a couple months. Different books recommend either dot notation or bracket notation. Personally I think, bracket notation looks much cleaner and easier to read.

There was this one line of code that I came across in some code and I'm not sure how would I write that using bracket notation

self.checked = !self.checked;

Thank for your help guys!

Answer Source

You can do it like this:

[self setChecked:![self checked]];

The "relative cleanliness" of the bracket vs. dot notation is in the eye of the beholder. Expressions like yours are OK, but longer chains of four or more look shorter, if not cleaner, when written using the dot notation. One advantage of bracket notation is that you do not need to cast an id to the target type; dot notation will not work without a cast:

NSArray *myArray = [NSArray arrayWithObject:[NSNumber numberWithInt:123]];
// This works:
NSLog(@"%d", [[myArray objectAtIndex:0] intValue]);
// This works too:
NSLog(@"%d", ((NSNumber*)[myArray objectAtIndex:0]).intValue);
// This does not compile:
NSLog(@"%d", [myArray objectAtIndex:0].intValue);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download