for each loop in Objective-C for accessing NSMutable dictionary

前端 未结 7 467
忘掉有多难
忘掉有多难 2020-11-30 16:45

I am finding some difficulty in accessing mutable dictionary keys and values in Objective-C.

Suppose I have this:

NSMutableDictionary *xyz=[[NSMutabl         


        
相关标签:
7条回答
  • 2020-11-30 17:03

    If you need to mutate the dictionary while enumerating:

    for (NSString* key in xyz.allKeys) {
        [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
    }
    
    0 讨论(0)
  • 2020-11-30 17:09

    I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.

    0 讨论(0)
  • 2020-11-30 17:11

    You can use -[NSDictionary allKeys] to access all the keys and loop through it.

    0 讨论(0)
  • 2020-11-30 17:16

    Fast enumeration was added in 10.5 and in the iPhone OS, and it's significantly faster, not just syntactic sugar. If you have to target the older runtime (i.e. 10.4 and backwards), you'll have to use the old method of enumerating:

    NSDictionary *myDict = ... some keys and values ...
    NSEnumerator *keyEnum = [myDict keyEnumerator];
    id key;
    
    while ((key = [keyEnum nextObject]))
    {
        id value = [myDict objectForKey:key];
        ... do work with "value" ...
    }
    

    You don't release the enumerator object, and you can't reset it. If you want to start over, you have to ask for a new enumerator object from the dictionary.

    0 讨论(0)
  • 2020-11-30 17:17
    for (NSString* key in xyz) {
        id value = xyz[key];
        // do stuff
    }
    

    This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though NSDictionary is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.

    Oh, I should add however that you should NEVER modify a collection while enumerating through it.

    0 讨论(0)
  • 2020-11-30 17:17

    Just to not leave out the 10.6+ option for enumerating keys and values using blocks...

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
        NSLog(@"%@ = %@", key, object);
    }];
    

    If you want the actions to happen concurrently:

    [dict enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                                  usingBlock:^(id key, id object, BOOL *stop) {
        NSLog(@"%@ = %@", key, object);
    }];
    
    0 讨论(0)
提交回复
热议问题