Search code examples
iosnsstringnsnull

Assign NSNull Object to NSString


I'm writing an iOS App where i need to get data from a SQL-Database over mobile Services from Azure.

After downloading the data I get a NSDictionary with all attributes from the SQL-Table. If an attribute is empty, the value is NSNull.

Is there a way to pass NSNull to NSString without an IF-Statement (I don't want to have 20 if statements..)?


Solution

  • I wrote a category just for dealing with this issue. I used it with Core Data but it should help you, too.

    @interface NSDictionary (Extensions)
    
    - (id)NSNullToNilForKey:(NSString *)key;
    
    @end
    
    @implementation NSDictionary (Extensions)
    
    - (id)NSNullToNilForKey:(NSString *)key
    {
        id value = [self valueForKey:key];
    
        return value != [NSNull null] ? value : nil;
    }
    
    @end
    

    Sample use:

    NSString *value = [dictionary NSNullToNilForKey:@"key"];