I'm looking for a class in Objective C similar to C#'s KeyValuePair (even without the generics). Just anything that has a first/second object. I can create my own with no problem, but I figure if one is already there, then there is no need to re-invent the wheel. I have not had any luck findind one myself... Does anyone know of one?
Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.
Dictionaries. NSDictionary. NSDictionary is a class used to organize objects in lists using keys and values. NSDictionary can maintain an index of objects and let you retrieve an object if you have the right key. Usually, the key will be an NSString object while the value will be whatever type of object you are ...
A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.
What about using plain C structs? It's "quicker" than writing an entire class.
typedef struct KeyValuePair {
const char *key;
const char *value;
} KeyValuePair;
//init like this
KeyValuePair kvp = {"yourkey", "yourvalue"}
Things to keep in mind:
How about a simple NSArray?
NSArray* kvp = [NSArray arrayWithObjects: key, value, nil];
// or, using boxed literals,
NSArray* kvp = @[key, value];
...
NSObject* key = [kvp firstObject];
NSObject* value = [kvp lastObject];
You could make a function to wrap +arrayWithObjects:
(and handle the case of a nil key or value which would trip up the simple approach)
Accessing the elements of an NSArray will probably be quicker than an NSDictionary.
So basically like a hashmap, right?
Use NSMutableDictionary
Example from here:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
// Add objects to a dictionary indexed by keys
[dictionary setObject:@"A Book about the Letter A" forKey:@"A"];
[dictionary setObject:@"A Book about the Letter B" forKey:@"B"];
[dictionary setObject:@"A Book about the Letter C" forKey:@"C"];
// Retrieve an object from a dictionary with a key
NSLog([dictionary objectForKey:@"B"]);
// Release a dictionary
[dictionary release];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With