Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting nil objects into an NSDictionary

Tags:

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?

Example:

[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              } 

This will crash when it gets to the stopped_drinking property. Any suggestions on how to handle this?

like image 944
jdog Avatar asked Dec 10 '12 23:12

jdog


People also ask

Can Nsarray contain nil?

arrays can't contain nil.

What is NSDictionary in Objective c?

Overview. The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.


2 Answers

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), } 
like image 155
Paul.s Avatar answered Oct 21 '22 14:10

Paul.s


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.

like image 37
CrimsonDiego Avatar answered Oct 21 '22 14:10

CrimsonDiego