将零个对象插入NSDictionary [英] Inserting nil objects into an NSDictionary
问题描述
如果我们有一个仅需要5个属性中的2个对象的API,而iPhone应用程序不要求它们实例化一个对象,则当在参数NSDicitionary中使用该对象时,该应用程序将崩溃.有人告诉我NSDictionary不会让您分配nil值,因为当它达到nil时,它认为它已经完成了. Objective-C是否可以将非零属性的对象吐出到NSDictionary中?
If we have an API that requires only 2 out of an objects 5 properties and iPhone app doesn't require them to instantiate an object, when the object is used in the params NSDicitionary the app will crash. I was told NSDictionary will not let you assign nil values, as when it reaches nil it thinks its finished. Does objective-c have a way to spit out an objects non-nil properties into an NSDictionary?
示例:
[Drunk alloc] init];
drunk.started_drinking = [NSDate date];
drunk.stopped_drinking (we don't set this because he is still a drunk)
drunk.fat = YES;
drunk.dumb = YES;
parameters:@{
@"auth_token" :token,
@"name" : drunk.name, @"date_started" : drunk.started_drinking,
@"date_stopped" : drunk.stopped_drinking,
@"prescribing_doctor" : drunk.fat,
@"pharmacy" : drunk.dumb
}
当它进入stopped_drinking属性时,它将崩溃.有关如何处理此问题的任何建议?
This will crash when it gets to the stopped_drinking property. Any suggestions on how to handle this?
推荐答案
这有点长,但是你可以做
It's a bit long winded but you could do
static id ObjectOrNull(id object)
{
return object ?: [NSNull null];
}
parameters:@{
@"auth_token" : ObjectOrNull(token),
@"name" : ObjectOrNull(drunk.name),
@"date_started" : ObjectOrNull(drunk.started_drinking),
@"date_stopped" : ObjectOrNull(drunk.stopped_drinking),
@"prescribing_doctor" : ObjectOrNull(drunk.fat),
@"pharmacy" : ObjectOrNull(drunk.dumb),
}
这篇关于将零个对象插入NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!