如何允许 NSMutableDictionary 接受“nil"值? [英] How to allow NSMutableDictionary to accept 'nil' values?

查看:63
本文介绍了如何允许 NSMutableDictionary 接受“nil"值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个声明:

 [custData setObject: [rs stringForColumnIndex:2]  forKey: @"email"];

其中从 SQLite3 d/b 获得的 [rs stringForColumnIndex:2] 的值为 nil.应用程序崩溃给我错误:

where [rs stringForColumnIndex:2] obtained from a SQLite3 d/b has a value of nil. The app crashes giving me the error:

NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: email)'

有没有办法防止这种情况发生?(比如 NSMutableDictionary 的设置?)

Is there a way to prevent this? (like a setting for NSMutableDictionary?)

更新:这就是我最终做的:

UPDATE: this is what I finally did:

[custData setObject: ([rs stringForColumnIndex:2] != nil? [rs stringForColumnIndex:2]:@"") forKey: @"email"];

推荐答案

有一个非nil 对象叫做NSNull 专门用于表示 nils 在plain" nil 不可接受的情况下.如果您将 nil 替换为 [NSNull null] 对象,NSDictionary 将接受它们.不过,您需要在出路时检查 NSNull.

There is a non-nil object called NSNull that is built specifically to represent nils in situations where "plain" nil is not acceptable. If you replace your nils with [NSNull null] object, NSDictionary will take them. You would need to check for NSNull on the way out, though.

请注意,这仅在您必须区分未设置的值和设置为 nil 的值时才重要.如果您的代码可以将缺失值解释nil,则您根本不需要使用NSNull.

Note that this is important only when you must differentiate between a value not being set and a value being set to nil. If your code is such that it can interpret a missing value as nil, you do not need to use NSNull at all.

这篇关于如何允许 NSMutableDictionary 接受“nil"值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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