Assign NSNull Object to NSString

依然范特西╮ 提交于 2019-12-11 16:12:12

问题


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


回答1:


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"];



回答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.



来源:https://stackoverflow.com/questions/21922026/assign-nsnull-object-to-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!