Bracket syntax in Objective-C
This question already has an answer here:
What are the details of “Objective-C Literals” mentioned in the Xcode 4.4 release notes?
- Xcode gives 3 syntax errors dealing with Stray '\342' in program
- Can an ObjC class object conform to a protocol?
- What is “the issue” with variable qualifier placement?
- Dot notation vs. message notation for declared properties
- !? Strange double unwrapped optional syntax in for_in ?
- What is this Objective-C syntax, ellipse style dot notation? “…”
3 Solutions Collect From Internet About “Bracket syntax in Objective-C”
It’s called object subscripting, as explained here
Its syntactic sugar, as
gets translated by the compiler to
NSDictionary implements subscripting too, so you can access an element in this fashion:
The cool (and potentially dangerous) feature is that this is generalized, so you can even have it on your own classes.
You just need to implement a couple of methods
(for indexed access)
- (id)objectAtIndexedSubscript:(NSUInteger)idx; - (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
or (for keyed access)
- (id)objectForKeyedSubscript:(id)key; - (void)setObject:(id)obj forKeyedSubscript:(id)idx;
and you they will be called whenever you use bracket notation on the instances of you custom class.
So you could end up coding a grid-based game and accessing the elements on the grid by
board[@"B42"]; // => [board objectForKeyedSubscript:@"B42"]
or moving a piece on the board by
board[@"C42"] = @"Troll"; => [board setObject:@"Troll" forKeyedSubscript:@"C42"];
Nice, but I wouldn’t abuse of it.
That’s literal syntax, introduced in Clang 3.4. You could however use the old syntax
[newSectionsArray objectAtIndex:index]. it’s the same thing.
newSectionsArray is probably an array (i.e. a contigous block of multiple objects of the same type) and
index an integer.
newSectionsArray[index] gives you the object at position
index (starting counting with 0).
- Objective C – Sort an array of string
- Building a chess board game in Sprite Kit using Swift?
- Fixed/absolute positioneing neglected in iOS when focusing on input
- Make Update to a live iPhone app
- Why should we release?
- Add constraints to generic parameters in extension
- Native-like momentum-scrolling on BODY in iOS webapp
- iOS GLSL. Is There A Way To Create An Image Histogram Using a GLSL Shader?
- How to check a version of a CocoaPods framework
- iTunes api, lookup by bundle ID?
- Java RMI server and Objective C client
- iOS Swift – Get the Current Local Time and Date Timestamp
- Vertically Centre Text in NSSecureTextField with subclassing
- UITabBarItem setFinishedSelectedImage: deprecated in iOS7
- Delete cookies UIWebView