How to use NSEnumerator with NSMutableDictionary?

 ̄綄美尐妖づ 提交于 2019-12-03 04:18:57

问题


How do I use NSEnumerator with NSMutableDictionary, to print out all the keys and values?

Thanks!


回答1:


Unless you need to use NSEnumerator, you can use fast enumeration (which is faster) and concise.

for(NSString *aKey in myDictionary) {
    NSLog(@"%@", aKey);
    NSLog(@"%@", [[myDictionary valueForKey:aKey] string]); //made up method
}

Also you can use an Enumerator with fast enumeration:

NSEnumerator *enumerator = [myDictionary keyEnumerator];

for(NSString *aKey in enumerator) {
    NSLog(@"%@", aKey);
    NSLog(@"%@", [[myDictionary valueForKey:aKey] string]); //made up method
}

This is useful for things like doing the reverse enumerator in an array.




回答2:


From the NSDictionary class reference:

You can enumerate the contents of a dictionary by key or by value using the NSEnumerator object returned by keyEnumerator and objectEnumerator respectively.

In other words:

NSEnumerator *enumerator = [myMutableDict keyEnumerator];
id aKey = nil;
while ( (aKey = [enumerator nextObject]) != nil) {
    id value = [myMutableDict objectForKey:anObject];
    NSLog(@"%@: %@", aKey, value);
}



回答3:


Here is the version without object search. Notice that objectForKey calling not exist. They use keyEnumerator and objectEnumerator both.

id aKey = nil;
NSEnumerator *keyEnumerator = [paramaters keyEnumerator];
NSEnumerator *objectEnumerator = [paramaters objectEnumerator];
while ( (aKey = [keyEnumerator nextObject]) != nil) {
    id value = [objectEnumerator nextObject];
    NSLog(@"%@: %@", aKey, value);
}


来源:https://stackoverflow.com/questions/1062110/how-to-use-nsenumerator-with-nsmutabledictionary

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