0

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..)?

Malloc
  • 15,434
  • 34
  • 105
  • 192
fahu
  • 1,511
  • 4
  • 17
  • 26
  • Damn it! But thank you for your quick answer! – fahu Feb 20 '14 at 23:33
  • 1
    Write a simple help method or function that returns what you want based on passing in either a string or `NSNull`. Then you don't need lots of `if` statements. Just a simple method or function call. – rmaddy Feb 20 '14 at 23:36
  • "Pass NSNull to NSString" makes no sense. You can certainly assign an NSNull to a pointer that's typed `NSString*`, though, without any real difficulty. Maybe you need to give us an example of your problem. – Hot Licks Feb 20 '14 at 23:47

2 Answers2

7

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"];
NathanAldenSr
  • 7,841
  • 4
  • 40
  • 51
2

You can't just assign it, but you can filter out all of the NSNull instances using something like this:

NSDictionary *dictionary = // data from server
NSDictionary *filteredDictionary = [dictionary mutableCopy];

NSSet *keysToRemove = [orig keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
    if (obj == [NSNull null]) {
        return YES;
    } else {
        return NO;
    }
}];
[filteredDictionary removeObjectsForKeys:[keysToRemove allObjects]];

Now you have the same dictionary except that every key with an NSNull has been removed.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170