字典的创建 一个元素 NSDictionary *dict1 = [NSDictionary dictionaryWithObject: @”rose” forKey: @”name”]; 多个元素 NSArray *obj = @[@”rose”, @”USA”]; NSArray *keys = @[@”name”, @”address”]; NSDictionary *dict2 = [NSDictionary dictionaryWithObjects: obj forKeys: keys]; 快速创建 NSDictionary *dict3 = @{@”name”: @”rose” , @”qq” : @”756111373”}; 访问字典元素 id obj1 = [dict3 objectForKey: @”qq”]; id obj2 = dict3[@”name”]; // 快速访问 计算长度(键值对的个数) NSUInteger count = dict3.count 可变字典 创建字典 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 添加元素 [dict setObject:@”rose” forKey:@”name”]; [dict setObject:@”USA” forKey:@”address”]; [dict setObject:@”756111373” forKey:@”qq”]; 删除元素 [dict removeObjectForKey:@”name”]; 打印字典 NSLog(@”%@”, dict1); 遍历字典 使用for循环 NSArray *keys = [dict allKeys]; for(int i = 0; i<dict.count; i++) { id obj = [dict objectForKey: keys]; } 使用block [dict enumerateObjectsAndKeysUsingBlock: ^(id obj, id key, Bool *stop) { NSLog(@”%@ : %@”, key, obj); }];
|