开发者

Copying an NSDictionary without empty values?

开发者 https://www.devze.com 2023-01-28 15:30 出处:网络
I\'m trying to create an NSDictionary 开发者_如何学运维with the dictionaryWithDictionary method.However, my first NSDictionary A may have some keys with empty values.How can I create B that doesn\'t h

I'm trying to create an NSDictionary 开发者_如何学运维with the dictionaryWithDictionary method. However, my first NSDictionary A may have some keys with empty values. How can I create B that doesn't have any keys with empty values? I'm doing all of this for the purposes of populating a UITableView with rows that correspond to each non-empty key in the NSDictionary.


How about something like this:

NSMutableDictionary *destDictionary = [NSMutableDictionary dictionaryWithCapacity:[sourceDictionary count]];
NSEnumerator *keyEnumerator = [[sourceDictionary allKeys] objectEnumerator];
id key;
while ( key = [keyEnumerator nextObject] )
    {
    NSString *object = [sourceDictionary objectForKey:key];
    if ([object length] == 0)
        continue;
    [destDictionary setObject:object forKey:key];
    }


You could also use a block test, filtering out the keys whose values have a length and create your new dictionary from that.

NSSet *keySet = [dictionary keysOfEntriesPassingTest:
                 ^(id key, id obj, BOOL *stop) {
                   return (BOOL)[obj length];
                 }];

NSArray *keys = [keySet allObjects];
NSArray *nonEmptyObjects = [dictionary objectsForKeys:keys notFoundMarker:@""];
NSDictionary *newDict = [NSDictionary dictionaryWithObjects:nonEmptyObjects
                                                    forKeys:keys];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号