how create array key and value in xcode?

25,587

Solution 1

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]);
}

Solution 2

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.

Solution 3

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.

Share:
25,587
user1825965
Author by

user1825965

Updated on August 09, 2020

Comments

  • user1825965
    user1825965 almost 4 years

    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.

  • user1825965
    user1825965 over 11 years
    Could you provide me simple example?
  • user1825965
    user1825965 over 11 years
    How to fetch this array by loop, show key and value by loop. fetching way NSString *valueStr = [dict objectForKey:@"Key2"]; I need to fetch by loop all key and value, i need to search value in array.
  • user1825965
    user1825965 over 11 years
    I would like know how i can fetch by loop?
  • Popeye
    Popeye over 11 years
    @user1825965 So you what to be able to get the values and keys in a for loop?