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];
精彩评论