Inserting nil objects into an NSDictionary

心不动则不痛 提交于 2019-12-02 17:10:46

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),
}

You cannot insert nil into collections (dictionaries, arrays, index sets, etc).

You can, however, insert [NSNull null] into them as this is what they made it for

Inserting objects into the dictionary becomes quite easy (if the property is nil, insert an NSNull instead). Then, when pulling things out of the dictionary, a quick if(myReturnedObject == [NSNull null]) will tell you if the returned value is valid, as NSNull is a singleton and thus every NSNull is in fact the same object.

Edit: Paul.s has an excellent example of insertion behavior for your case, complete with ternary operator usage.

Edit Again: Despite the below comment, it is factually confirmed in the Apple docs linked above that NSNull does not crash when added to collections.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!