Search code examples
objective-cmacosfast-enumeration

Is it possible to use fast enumeration on a NSMutableDictionary?


I have the following method (it is an instance method of ShoppingCart):

- (void) showShoppingCartProducts
 {
   for (Product *eachProduct in products)
    {
      [eachProduct logName]
    }
}

I have another method (it is an instance method of ShoppingCart):

- (void) addProduct: (Product *) newProduct {
    [products objectForKey: newProduct.name];
}

It is supposed to iterate through each (Product *) eachProduct in (NSMutableDictionary *) products.

logName does the following (it is an instance method of Product):

- (void) logName
{
  NSLog(@"%@", self.name);
}

Here is my main() function

int main(int argc, const char * argv[]) {

    ShoppingCart* myShoppingCart = [[ShoppingCart alloc] init];

    Product* myProduct = [[Product alloc] init];

    myProduct.name = @"My Latest Product";

    [myShoppingCart addProduct: myProduct];

    [myShoppingCart showShoppingCartProducts];

    return 0;
}

After running the program, it returns 0, but displays nothing.

Is it possible to use fast enumeration on a NSMutableDictionary?


Solution

  • This:

    NOTE: [myShoppingCart addProduct: myProduct] just adds (Product ) myProduct to a NSMutableDictionary products in (ShoppingCart *) myShoppingCart

    is not adequate explanation. There's no such thing as "just adding an object to an NSMutableDictionary". You set a value for a key in dictionaries. Which is myProduct, the value or the key? If it's the value, what is the key? If it's the key, what is the value?

    To answer the basic question: yes, you can fast enumerate over a dictionary. The keys are enumerated. If you want the value for each key, you then have to look that up using -objectForKey: or the subscripting syntax.

    If you think you're adding an object to a dictionary (or any other collection) but then the dictionary (collection) seems to be empty, that's probably because you're dealing with a nil pointer and not an actual collection. You neglected to create the collection and store a strong reference to it.


    You've edited the question to show this method:

    - (void) addProduct: (Product *) newProduct {
        [products objectForKey: newProduct.name];
    }
    

    That method does not add the product to the dictionary. -objectForKey: looks up an object that may already be in the dictionary by its key. It doesn't modify the dictionary. You probably meant to do this:

    - (void) addProduct: (Product *) newProduct {
        [products setObject:newProduct forKey:newProduct.name];
    }
    

    Given that you succeed in adding Product instances to the dictionary and the name is an NSString*, your enumeration should look like this:

    for (NSString* name in products)
    {
        Product* product = [products objectForKey:name];
        [product logName]
    }