Daniel Hernández Daniel Hernández - 1 year ago 119
Objective-C Question

Insert a value for key into NSMutableArray

I think this could be a very easy question for you.

But I have searched a lot and I don't know if I am very fool or I am using the wrong class (


I want to add an object for a specific key so that I can retrieve it later.

For example:

NSMutableArray *grisOcurrencias = [[NSMutableArray alloc] init];

[grisOcurrencias setValue:ocurrencia forKey:[NSString stringWithFormat: @"%f", pixelVal]];

But the array is not getting inserted in the array, if I do something like:

[grisOcurrencias addObject: ocurrencia]

The object is inserted.

Am I doing something wrong?

Other thing... I want to recover the object by its key, what method should I use?

Thanks a lot

Answer Source

You are looking for NSMutableDictionary, not NSMutableArray. Dictionaries store objects based on a key, whereas arrays store objects based on an index.

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setObject:something forKey:@"Some Key"];

// ... and later ...

id something = [dict objectForKey:@"Some Key"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download