Reputation: 1168
I want to save some object in form of collection (object,key) in objective C. I found NSMutableDictionary
is the fit to that, but the problem is that I cannot get back the object I want (last added object, first added object ...). Is there a better way of doing so?
Upvotes: 1
Views: 182
Reputation: 86
NSMutablearray is best approach if you want to get last added object , or object by index . object added first is at object index 0 and object added last in at [count-1] index
Upvotes: 0
Reputation: 4744
You can get back your object by using this object's key you added to Dictionary:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"A" forKey:@"a"];
NSString *strA = [dict objectForKey:@"a"];
Put your keys to an NSMutableArray will help you get last/first key.
Hope that help!
Upvotes: 1
Reputation: 5316
Dictionaries are for accessing data when you have a key. They are not ordered containers.
If you need to retrieve data based on when you added it to a container you need a LIFO (aka stack), FIFO (aka queue) or deque (aka double-ended queue) kind of container. You can read about them on wikipedia for a starter, but I suggest you read at least one decent algorithm and data structures book, if you want to become a programmer.
AFAIK there are no predefined classes that implement those abstractions in cocoa, but they are all easy to do with arrays. NSArray
has lastObject
and objectAtIndex:
methods, and NSMutableArray
also have addObject:
, insertObject:atIndex:
, removeLastObject
and removeObjectAtIndex:
methods that basically are the primitives for LIFO/FIFO/deque access (assuming you use 0 when an index is required by those methods).
Upvotes: 0
Reputation: 7351
For a Key-Value pair, an NSDictionary or NSMutableDictionary is the correct solution.
There will only be one value for any given key, and setting a new value will overwrite the old one.
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
[myDictionary setValue:@"World" forKey:@"Hello"];
NSLog(@"Hello %@", [myDictionary objectForKey:@"Hello"]); // prints Hello World
[myDictionary setValue:@"StackOverflow" forKey:@"Hello"];
NSLog(@"Hello %@", [myDictionary objectForKey:@"Hello"]); // prints Hello StackOverflow
[myDictionary setValue:nil forKey:@"Hello"];
NSLog(@"Hello %@", [myDictionary objectForKey:@"Hello"]); // prints Hello (null)
Upvotes: 1