Assign NSNull Object to NSString
Asked Answered
R

2

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

Redcoat answered 20/2, 2014 at 23:31 Comment(3)
Damn it! But thank you for your quick answer!Redcoat
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.Overwrite
"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.Harvin
K
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"];
Kinakinabalu answered 20/2, 2014 at 23:47 Comment(4)
You're welcome. :) I use this category extensively when converting JSON structures to Core Data entities, since the JSON deserializer I use deserializes null values to [NSNull null].Kinakinabalu
exactly the thing i want to use it!Redcoat
Could you list steps on how to implement this?Stickle
@Stickle Sorry, I haven't done iOS programming in years, but it should be as simple as just creating a new class file and header file, no?Kinakinabalu
Q
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.

Queenqueena answered 20/2, 2014 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.