Basic data supporting NSNull

Is it possible to get Core Data for an NSNull assignment? I use JSONKit and by default it assigns NSNull . I would prefer my deserialization to be like this:

 - (void)deserialize:(NSDictionary *)dictionary { self.name = [dictionary objectForKey:@"name"]; } 

Instead of this:

 - (void)deserialize:(NSDictionary *)dictionary { NSNull *null = [NSNull null]; NSString *value = [dictionary objectForKey:@"name"]; self.name = (value != null) ? value : nil; } 
+4
source share
3 answers

One thought would be to create a category for NSDictionary. Then the category could contain this behavior.

+4
source

I do not think it is possible using CoreData for this.

But if the passphrase, if you're looking, you can just use macros:

 #define NULL_NIL(_O) _O != [NSNull null] ? _O : nil #define DICT_GET(_DICT, _KEY) NULL_NIL([_DICT objectForKey:_KEY]) #define DICT_GET_INT(_DICT, _KEY) [DICT_GET(_DICT, _KEY) intValue] ... 

Not that I would say optimized, but brings concise and readable code:

 - (void)deserialize:(NSDictionary *)dictionary { self.name = DICT_GET(dictionary, @"name"); } 
+4
source

If you need to deal with several types of collections (and not just dictionaries), you can create a category in NSNull:

 @implementation NSNull (NSNull_nilIfNull) + (id)nilIfNull:(id)object { if (object == [self null]) { return nil; } return object; } @end 

Implementation:

 theValue = [NSNull nilIfNull:[array objectAtIndex:someIndex]]; 

But I have to say that this adds unnecessary verbosity. I like the idea of ​​using Vincent G preprocessor macros to read code.

+2
source

All Articles