Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how create array key and value in xcode? [closed]

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.

like image 651
user1825965 Avatar asked Nov 15 '12 10:11

user1825965


3 Answers

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]);
}
like image 95
Dave Avatar answered Oct 17 '22 03:10

Dave


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.

like image 27
Popeye Avatar answered Oct 17 '22 04:10

Popeye


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.

like image 43
Antonio MG Avatar answered Oct 17 '22 05:10

Antonio MG