Inserting nil objects into an NSDictionary

原來無法插入 nil 進去 NSDictionary, 為何要做的這麼不friendly? 在底層幫忙轉一下,不就好了?難道他們工程師有潔癖?


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.

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.

https://developer.apple.com/documentation/foundation/nsnull


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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *