I am a new Iphone developer i need your help,
Any one provide me creating array with key and value, and how can fetch in xcode.
This the NSMutableDictionary. You can search for sample codes. For example: Create dict
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:@"object1" forKey:@"key1"];
Printing all keys and values of a Dict:
for (NSString* key in [dictionary allKeys]) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
You can use an NSDictionary
or NSmutabledictionary
to achieve this you don't need to use and NSArray
. Here is an example of how it works.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // Don't always need this
// Note you can't use setObject: forKey: if you are using NSDictionary
[dict setObject:@"Value1" forKey:@"Key1"];
[dict setObject:@"Value2" forKey:@"Key2"];
[dict setObject:@"Value3" forKey:@"Key3"];
then you can retrieve a value for a key by just doing.
NSString *valueStr = [dict objectForKey:@"Key2"];
this will give the value of Value2 in the valueStr string.
to add objects to a none Mutable dictionary NSDictionary
just do
NSDictionary *dict2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"Value1", @"Key1", @"Value2", @"Key2", nil];
then just retrieve it the same way as an NSMutableDictionary
. The difference between the two is that a Mutable
dictionary can be modified after creation so can add objects to it with the setObject:forKey
and remove objects with the removeObjectFroKey:
whereas the none mutable dictionary can not be modified so once it has been created your stuck with it until it has been released, so no adding or remove objects.
Hope this helps.
That's exactly what a NSDictionary / NSMutableDictionary does:
NSMutableDictionary *myDictionary = [[ NSMutableDictionary alloc] init];
[ myDictionary setObject:@"John" forKey:@"name"];
[ myDictionary setObject:@"Developer" forKey:@"position"];
[ myDictionary setObject:@"1/1/1984" forKey:@"born"];
The difference is that, in the mutable one, you can add/modify entries after creating it, but not in the other.
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