Accessing keys in NSDictionary using [key] notation?

拥有回忆 提交于 2019-12-04 05:46:57
Aditya Vaidyam

This is a new addition to Xcode 4.4+ and relies on Apple's LLVM+Clang compiler. It's a new feature :) Arrays can also be accessed with the same notation: myObjectArray[4].

If you're interested in adding this new feature to your own classes (called subscripting), there's a few methods you can implement:

@interface NSArray(Subscripting)
- (id)objectAtIndexedSubscript:(NSUInteger)index;
@end

@interface NSMutableArray(Subscripting)
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)index;
@end

@interface NSDictionary(Subscripting)
- (id)objectForKeyedSubscript:(id)key;
@end

@interface NSMutableDictionary(Subscripting)
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;
@end

If you implement any of these methods on your own classes, you can subscript on them. This is also how you can add this feature to OS X 10.7 too!

Refer to "Modern Objective-C", introduced in iOS 6.

See the WWDC 2012 video: Migrating to Modern Objective-C.

So, no, the feature is not really new and you have overlooked it... ;-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!