2011-05-27 111 views
4

是否有可能獲得核心數據以允許分配NSNull?我正在使用JSONKit,它默認爲分配NSNull。我寧願能夠做我的反序列化這樣的:核心數據支持NSNull

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

取而代之的是這樣的:

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

回答

4

一個想法是創建的NSDictionary類別。該類別可能包含此行爲。

+0

謝謝。聽起來是一個好主意。 – 2011-05-27 18:59:01

4

我認爲這不可能與CoreData這樣做。

但是,如果代碼簡潔,如果你在找什麼,你可以只使用宏:

#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] 
... 

不是我想說優化,但帶來了簡明易讀代碼:

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

如果您必須處理多種集合類型(不僅僅是字典),您可以在NSNull上創建一個類別:

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

實現:

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

但我必須說,這增加了不必要的冗長。我喜歡使用Vincent G的預處理器宏來保持代碼可讀性的想法。