【问题标题】:How to use NSEnumerator with NSMutableDictionary?如何将 NSEnumerator 与 NSMutableDictionary 一起使用?
【发布时间】:2010-11-06 22:06:09
【问题描述】:

如何使用 NSEnumerator 和 NSMutableDictionary 打印所有键和值?

谢谢!

【问题讨论】:

    标签: iphone nsenumerator


    【解决方案1】:

    除非你需要使用 NSEnumerator,否则你可以使用快速枚举(这样更快)并且简洁。

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

    您还可以使用具有快速枚举功能的 Enumerator:

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

    这对于在数组中执行反向枚举器之类的事情很有用。

    【讨论】:

    • 不要忘记,如果需要,您也可以仅从字典中枚举值:for (NSString *value in [myDictionary allValues])。
    • 是的,但 -allValues 确实会创建一个中间(自动释放)数组,因此请注意所需的额外存储空间。
    • NSLog(@"%@) 而不是NSLog("%@)
    • @KendallHelmstetterGelner 您还可以使用 [myDictionary objectEnumerator] 枚举所有对象,这不会创建中间数组。
    • 另外,将枚举器访问器直接放在 for 语句中是非常好的,例如for(NSString *aKey in [myDictionary keyEnumerator]),因为in 之后的表达式只计算一次。
    【解决方案2】:

    来自NSDictionary class reference

    您可以使用分别由keyEnumeratorobjectEnumerator 返回的NSEnumerator 对象按键或按值枚举字典的内容。

    换句话说:

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

    【讨论】:

    • 您还可以在 Objective-C 2.0 中使用快速枚举以相同的顺序枚举键 - 只需使用 for (NSString *key in myMutableDict) { ... } 代替。
    【解决方案3】:

    这里是没有对象搜索的版本。请注意 objectForKey 调用不存在。 他们同时使用 keyEnumerator 和 objectEnumerator。

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

    【讨论】:

    • 订单有保障吗?即,您确定 objectEnumerator 返回的值与 keyEnumerator 返回的值相关联吗?
    猜你喜欢
    • 2011-05-27
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2023-03-13
    • 2014-09-25
    • 2016-01-30
    • 2015-12-13
    • 2020-09-15
    相关资源
    最近更新 更多