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

2019-06-23 16:15发布

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.

4条回答
在下西门庆
2楼-- · 2019-06-23 16:23

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.

查看更多
Bombasti
3楼-- · 2019-06-23 16:31

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.

查看更多
爷、活的狠高调
4楼-- · 2019-06-23 16:33

If you don't need to add object anymore, you can create a non mutable dictionary:

NSDictionary* dict= @{ @"key1" : @"value1" , @"key2" : @"value2" };

If you don't need key value pairs that's an array:

NSArray* array= @[ @"value1" , @"value2", @"value3" ];
查看更多
The star\"
5楼-- · 2019-06-23 16:42

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]);
}
查看更多
登录 后发表回答