NSDictionary - 避免 nils
我在视图控制器中有很多文本字段(大约 20 个)。用户填写文本字段(有些可能为空)后,我创建 ab NSDictionary 并将其发送到我的数据中心类。我正在创建的 NSDictionary 看起来像这样:
textfield1 -> textfield1_value
textfield2 -> textfield2_value
textfield3 -> textfield3_value
textfield4 -> textfield4_value
问题是,每当用户将字段留空时,就会将 nil 放入值中。这会导致 NSDictionary 突然/过早地初始化(如果这是正确的词)。为每个 20 个文本字段检查一个 nil 是我唯一的选择吗?我觉得必须有更好的方法。谢谢。
很抱歉造成混乱。我正在像这样初始化 NSDictionary:
[NSDictionary dictionaryWithObjectAndKeys: obj1, key1, obj2, key2, ..., nil];
I have a lot of textfields(about 20) in a view controller. After the user fills out the textfields (some maybe empty), I create ab NSDictionary and send it to my datacenter class. The NSDictionary I am creating looks like this:
textfield1 -> textfield1_value
textfield2 -> textfield2_value
textfield3 -> textfield3_value
textfield4 -> textfield4_value
The thing is, anytime the user leaves a field blank, a nill is put into value. This causes the NSDictionary to be initialized abruptly/prematurely (if thats the right word). Is checking for a nil for each and every 20 textfield my only option here? I feel like there's got to be a better way. Thanks.
Sorry about the confusion. I am initializing the NSDictionary like this:
[NSDictionary dictionaryWithObjectAndKeys: obj1, key1, obj2, key2, ..., nil];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 setObject:forKey: 方法,则应注意不要传递 nil 作为值,这将引发 NSInvalidArgumentException。
如果您使用 setValue:forKey: 方法,将 nil 设置为值实际上会从字典中删除键,从而节省内存。在您根本不需要它的情况下,此方法对于从字典(实际上是内存)中删除键非常有用。如果您使用此方法,则不必检查文本字段中是否为 nil,这也可以节省您一些时间。
If you use setObject:forKey: method, you should be careful not to pass a nil as value, which will raise an NSInvalidArgumentException.
If you use setValue:forKey: method, setting nil as the value actually removes the key from the dictionary, which saves the memory. This method will be really helpful to remove a key from the dictionary(actually a memory) in situations where you don't want it at all. If you use this method you don't have to check for nil in the text fields, which saves you some time too.
为了将
nil
存储在NSMutableDictionary
中,您应该用[NSNull null]
包装它,因为不能放入nil< /code> 中。
检查文本字段是否为空的方式实际上取决于您的代码,但如果您打算存储这样的值,则必须检查
nil
。In order to store
nil
in aNSMutableDictionary
, you should wrap it with[NSNull null]
, cause can't putnil
in.The way you will check if a text field is empty actually depends on your code, but checking for
nil
is compulsory, if you plan to store such a value in.