// // main.m // NSDictionary // // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { // 1.如何创建 NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"lnj" forKey:@"name"]; NSString *name1 = [dict1 objectForKey:@"name"]; NSLog(@"name = %@", name1); //lnj NSLog(@"dict1 = %@", dict1); //dict1 = {name = lnj;} // 注意: key和value 是一一对应 NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:@[@"lnj", @"30", @"1.75"] forKeys:@[@"name", @"age", @"height"]]; NSLog(@"dict2 = %@", dict2); //{age = 30;height = "1.75";name = lnj;} NSLog(@"%@ %@ %@", [dict2 objectForKey:@"name"], [dict2 objectForKey:@"age"], [dict2 objectForKey:@"height"]); //NSDictionary *dict3 = @{key:value}; NSDictionary *dict4 = @{@"name": @"lnj"}; NSLog(@"%@", dict4[@"name"]); NSDictionary *dict5 = @{@"name":@"lnj", @"age":@"30", @"height":@"1.75"}; NSLog(@"dict5 = %@", dict5);//{age = 30;height = "1.75";name = lnj;} NSLog(@"%@ %@ %@", dict5[@"name"], dict5[@"age"], dict5[@"height"]); // 2.字典的遍历 NSDictionary *dict6 = @{@"name":@"lnj", @"age":@"30", @"height":@"1.75"}; // 2.1如何获取字典中key和value的个数, 在字典中key称之为键, value称之为值 NSLog(@"count = %lu", [dict6 count]); for (int i = 0; i < dict6.count; ++i) { // 获取字典中所有的key NSArray *keys = [dict6 allKeys]; // 取出当前位置对应的key NSLog(@"%@", keys[i]); NSString *key = keys[i]; NSString *value = dict6[key]; NSLog(@"key = %@, value = %@", key, value); } // 如何通过forin遍历字典, 会将所有的key赋值给前面的obj for (NSString *key in dict6) { NSLog(@"%@", key); NSString *value = dict6[key]; NSLog(@"key = %@, value = %@", key, value); } [dict6 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"key = %@, value = %@", key, obj); }]; // 3.字典文件读写 NSDictionary *dict7 = @{@"name":@"lnj", @"age":@"30", @"height":@"1.75"}; // XML 扩展名plist [dict7 writeToFile:@"/Users/mctc/Desktop/a.plist" atomically:YES]; // 注意: 字典和数组不同, 字典中保存的数据是无序的 NSDictionary *newDict8 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/mctc/Desktop/a.plist"]; NSLog(@"%@", newDict8);// {age = 30;height = "1.75";name = lnj;} NSArray *arr9 = @[@10, @20, @30, @5]; [arr9 writeToFile:@"/Users/mctc/Desktop/a.plist" atomically:YES]; return 0; }
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/7441030.html,如需转载请自行联系原作者