// // main.m // OC05-task-02 // // Created by Xin the Great on 15-1-25. // Copyright (c) 2015年 Xin the Great. All rights reserved. // #importint main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... ///////////////NSMutableDictionary--可變字典/////////////// //初始化可變字典 //空的字典 NSMutableDictionary *dic1 = [NSMutableDictionary dictionary]; NSLog(@"dic1 is %@", dic1); //給字典預期的一個空間 NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithCapacity:10]; //添加元素 [dic1 setObject:@"value1" forKey:@"key1"]; [dic1 setObject:@"value2" forKey:@"key2"]; [dic1 setObject:@"value3" forKey:@"key3"]; //設置鍵值對,如果key已經存在,則是修改key所對應的value, 如果不存在,則創建一個新的鍵值對 [dic1 setObject:@"value4" forKey:@"key4"]; NSLog(@"dic1 is %@", dic1); //刪除元素 //刪除指定的元素 [dic1 removeObjectForKey:@"key2"]; NSLog(@"dic1 is %@", dic1); //刪除所有的元素 [dic1 removeAllObjects]; NSLog(@"dic1 is %@", dic1); //字典的遍歷 NSDictionary *dic = @{@"k1":@"v1", @"k2":@"v2", @"k3":@"v3", @"k4":@"v4", @"k5":@"v5",}; //傳統遍歷 NSArray *keys = [dic allKeys]; for (int i = 0; i < dic.count; i++) { //獲取key NSString *key = keys[i]; NSString *value = dic[key]; NSLog(@"value[%@] is %@", key, value); } NSLog(@"------------------------------"); //快速遍歷, 快速遍歷效率要高於傳統遍歷 for (NSString *key in dic) { NSString *value = dic[key]; NSLog(@"value[%@] is %@", key, value); } } return 0; }