使用 [key] 表示法访问 NSDictionary 中的键? [英] Accessing keys in NSDictionary using [key] notation?

查看:58
本文介绍了使用 [key] 表示法访问 NSDictionary 中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到我可以使用 objectForKey: 和 dict[key] 访问 NSDictionary?

I have just realised that I can access NSDictionary using both objectForKey: and dict[key]?

NSDictionary *coordsDict = @{@"xpos": @5.0, @"ypos": @7.2, @"zpos": @15.7};
NSLog(@"XPOS: %@", coordsDict[@"xpos"]);
NSLog(@"XPOS: %@", [coordsDict objectForKey:@"xpos"]);

谁能告诉我这是否一直对我隐瞒,或者是否最近对语言进行了一些更改?

Can anyone tell me if this has been hiding from me all along or if its some fairly recent change to the language?

该问题一般不涉及新的字符串文字,而是更具体地涉及使用与 NSArray 相同的字符串文字语法访问 NSDictionary.我显然忽略了这一点,只是想检查一下何时添加了此特定语法.

The question does not generically refer to the new string literals, but more specifically to accessing NSDictionary with the same string literal syntax you would use for NSArray. I obviously overlooked this and just wanted to check when this particular syntax was added.

推荐答案

这是 Xcode 4.4+ 的新增功能,依赖于 Apple 的 LLVM+Clang 编译器.这是一个新特性 :) 数组也可以用相同的符号访问:myObjectArray[4].

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

如果您在自己的类上实现了这些方法中的任何一个,则可以在它们上添加下标.这也是您可以将此功能添加到 OS X 10.7 的方法!

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!

这篇关于使用 [key] 表示法访问 NSDictionary 中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆