objective-c语法——Dictionary
// // main.m // Dictionary // // Created by RD-Neil on 1/21/13. // Copyright (c) 2013 RD-Neil. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; /* 做过Java语言或者 C语言开发的朋友应该很清楚关键字map 吧,它可以将数据以键值对儿的形式储存起来, 取值的时候通过KEY就可以直接拿到对应的值,非常方便。在Objective-C语言中词典对象就是做这个事情 的,不过在同一个词典对象中可以保存多个不同类型的数据,不像Java与C只能保存声明的相同类型的数据, 它的关键字为NSDictionary与NSMutableDictionary。阅读过我之前文章的朋友应该从关键字的结构就 可以看出这两个的区别。很明显前者为不可变词典,或者为可变词典。 */ // 创建动态字典,初始化长度为10 NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:10]; // 向字典中添加数据 [mutableDictionary setObject:@"0.0" forKey:@"32.0"]; [mutableDictionary setObject:@"100.0" forKey:@"212.0"]; [mutableDictionary setObject:@"20.0" forKey:@"68.0"]; [mutableDictionary setObject:@"-100.0" forKey:@"-148.0"]; NSLog(@"mutableDictionarr:"); // 通过key找到value NSLog(@"%@",[mutableDictionary objectForKey:@"32.0"]); NSLog(@"%@",[mutableDictionary objectForKey:@"212.0"]); NSLog(@"%@",[mutableDictionary objectForKey:@"68.0"]); NSLog(@"%@",[mutableDictionary objectForKey:@"-148.0"]); // 打印可变字典中所有key NSLog(@"all keys: %@", [mutableDictionary allKeys]); // 打印可变字典中所有value NSLog(@"all values: %@", [mutableDictionary allValues]); // 删除单个元素 [mutableDictionary removeObjectForKey:@"32.0"]; // 删除字典中所有元素 [mutableDictionary removeAllObjects]; // 增加一个元素 [mutableDictionary setObject:@"00000.0" forKey:@"32.0"]; NSLog(@"%@",[mutableDictionary objectForKey:@"32.0"]); // 静态字典 NSDictionary *normalDictonary = [NSDictionary dictionaryWithObjectsAndKeys:@"Jenny", @"d1", @"Neil", @"d2", nil]; // 通过key找到value NSString *d1 = [normalDictonary objectForKey:@"d1"]; NSLog(@"normalDictionarr:"); // 字典中所有的key NSLog(@"All keys: %@", [normalDictonary allKeys]); // 字典中所有的value NSLog(@"All values %@", [normalDictonary allValues]); NSLog(@"%@", d1); [pool release]; }