使用 NSDictionaries
我有许多 NSString 对象想要保存到 NSDictionary 中。
NSDictionary 是如何用键初始化的,是否需要在那里设置值,然后或者可以仅使用键和稍后设置的对象来设置字典?
I have a number of NSString objects I want to save into an NSDictionary.
How is an NSDictionary initialized with the keys and do the values need to be set there and then or can the dictionary be setup using just the keys and the objects later set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字典可以初始化为空或
(value,key)
对列表。在 Objective-C 中,仅使用键而不是值来初始化字典是无用/无意义的,因为它相当于 void 初始化。
如果您想创建一个字典并希望稍后能够设置对象,则必须使用
NSMutableDictionary
,它没有通过其setObject:forKey 静态初始化其数据:方法。
A dictionary can be initialized both as empty or as a list of
(value,key)
pairs.Initializing the dictionary just with keys and not values is useless/meaningless in Objective-C, since it will be equivalent to a void initialization.
If you want to create a dictionary and want to be able to set objects later, you have to use a
NSMutableDictionary
, that has not a static initialization of its data, through itssetObject:forKey:
method.首先是 NSDictionary 文档和NSMutableDictionary
您可以创建通过传递
[NSNull null]
作为该键的对象,仅包含键的NSMutableDictionary
。在这里使用可变字典很重要,否则在创建字典后将无法更改它,并且只有键而不是对象的字典没有什么用处。这就是 NSNull 用于:为不允许 nils 的集合类型提供 null 值。
To start with here's a link to the NSDictionary documentation, and NSMutableDictionary
You can create a
NSMutableDictionary
with just keys by passing[NSNull null]
as the object for that key. It's important to use a mutable dictionary here otherwise you won't be able to change the dictionary after you've created it, and a dictionary that just has keys instead of objects is of little use.That is what NSNull is for: to provide null values for collection types that don't allow nils.