Copying an NSDictionary without empty values?

雨燕双飞 提交于 2019-12-11 06:31:33

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4350742/copying-an-nsdictionary-without-empty-values

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