Reputation: 15653
I want to be able to add objects to an NSArray
and access them with Keys. Currently the way im doing it is creating a seperate NSDictionary
of key-value pairs where the value is an integer number representing the index in my NSArray
. This seems like an extra step to me.
If my understanding of NSDictionary
is correct, only 'values' can be stored: a pointer to an object cannot.
Surely there must be an equivalent NSDictionary
type function that allows objects to be stored and accessed with a key? I have looked through the documentation, but cant seem to find any answers, unless im missing something obvious.
Upvotes: 0
Views: 874
Reputation: 256
I think I understand your problem. My suggestion for you is to use NSMutableArray
and macros, like:
NSMutableArray *array=[[NSMutableArray alloc]init];
#define SOME_MACRO 0
id someObject;
[array insertObject:someObject atIndex:SOME_MACRO];
id getterObject=[array objectAtIndex:SOME_MACRO];
Upvotes: 0
Reputation:
In short, no.
An array (NSArray
) is an ordered collection of references to objects, so simply said, an ordered collection of objects.
As opposed to dictionaries, which are unordered and values are accessed by keys.
You understanding of collections is probably wrong, you don't store values, but pointers (references).
The extra step is necessary if you need to store the references in an array, but in this case, you should consider using a dictionary. An option is to use keys that take care of the order.
For example :
[myDictionary objectForKey:@"1"];
could be an equivalent of :
[myArray objectAtIndex:1];
Upvotes: 1
Reputation: 2230
I have no experience in Cocoa but looking at the documentation it seems like NSDictionary
(or at least NSMutableDictionary
) should handle your request (without you using NSArray).
Upvotes: 0
Reputation: 9866
You can store objects in NSDictionary
and can be accessed via keys
...
Upvotes: 1
Reputation: 10251
NSDictionary is to store key value pairs. if you are adding key value pair after you created the dictioanry, use NSMutableDictionary class . example,
[dictionaryObject setObject:@"" forKey:@"abc"];
Upvotes: 1
Reputation: 11174
Thats wrong, you can store objects in a NSDictionary. Look at the method dictionaryWithObjects:forKeys:
or dictionaryWithObjectsAndKeys:
Upvotes: 0