替换 Objective-C 字典中 nil 的使用
我正在研究 iPhone SDK,对 Objective-C 还很陌生。现在我正在使用 NSUserDefaults 来保存和恢复我的 iPhone 应用程序上的设置。为了保存已经创建的类,我将它们编码成字典形式,然后保存NSdictionary。
我的问题是我找不到合理的方法来以合理的方式在字典中存储非值(即为零的类变量)。更具体地说,假设我有一个“Dog”类,它有 NSString *tail-color。假设我正在尝试保存没有尾巴的狗的类实例,因此该实例的尾巴颜色为零。将狗保存为字典的合理方法是什么?它不会让我将 nil 保存到 NSdictionary 中。 @"" 不好,因为如果我这样做 if(@""),@"" 就是 true。我希望它像 nil 这样是假的。
我希望我的问题有意义,感谢您的帮助!
I'm working in the IPhone SDK, and am pretty new to objective-c. Right now I'm working with NSUserDefaults to save and restore setting on my IPhone app. In order to save the classes that have been created, I encode them into dictionary form, and then save the NSdictionary.
My problem is that I can't find a reasonable way to store a non-value (I.E. a class variable that is nil) in the dictionary in a reasonable way. To be more specific, lets say I have a class "Dog" and it's got NSString *tail-color. Lets say I'm trying to save a class instance of a dog without a tail, so tail-color for that instance is nil. What is a reasonable way of saving dog as a dictionary? It won't let me save nil into the NSdictionary. @"" isn't good, because if I do if(@""), @"" is true. I would like it to be false like nil.
I hope my question makes sense, and thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您没有为该键存储任何内容,则在调用
objectForKey:
时将返回nil
。如果您在读入数据时检查nil
,这样就足够了吗?或者,您可以使用objectsForKeys:notFoundMarker:
来返回默认值,而不是nil
。因此,对于您没有的值,不要在字典中存储任何内容,并使用一种策略来处理读取时丢失的值。
您可以使用 NSNull,但这在我看来并不标准。
If you don't store anything for that key,
nil
will be returned when you callobjectForKey:
. If you check fornil
when reading the data in, would that be enough? Optionally, you can useobjectsForKeys:notFoundMarker:
that will return a default value instead ofnil
.So, store nothing at all in the dictionary for a value you don't have, and use a strategy for handling that value missing when reading.
You could use
NSNull
, but that doesn't feel standard, IMO.您可以使用 NSNull。像这样实例化它:
我建议
You can use NSNull. Instantiate it like this:
I would recommend Archiving to save and restore your objects, however.
您应该使用 NSNull 表示集合中的 nil 对象
You should use NSNull to represent nil objects in collections
最好的解决方案是不保存在您的情况下为“nil”的值。在读取时,如果给定键不存在该值,字典将返回“nil”。
The best solution is to not save the values which are 'nil' in your case. While reading if the value is not present for your given key the dictionary will return you 'nil'.