Daniel Hernández Daniel Hernández - 2 months ago 12x
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


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"];