標籤:
NSDictionary
不可變的字典
建立字典的方法
// 建立字典的方式 NSDictionary *dy = [NSDictionary dictionaryWithObject:@"a"forKey:@"b"]; NSDictionary *dy1 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"b",@"c",@"d" ,nil]; // 快速建立字典 // 重複key值,重複的不能儲存到字典中 NSDictionary *dy2 = @{@"we":@"haha", @"we":@"ha"}; NSLog(@"%@",dy); NSLog(@"%@",dy1); NSLog(@"%@",dy2);
擷取字典的長度
// 擷取字典長度 NSDictionary *dy2 = @{@"we":@"haha", @"w":@"ha"}; NSLog(@"%lu",dy2.count); // 輸出2 // 如果key值重複,長度不計算在內 NSDictionary *dy2 = @{@"we":@"haha", @"we":@"ha"}; NSLog(@"%lu",dy2.count); //輸出1
字典的遍曆
NSDictionary *dy1 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"b",@"c",@"d" ,nil]; // 快速建立字典 // 重複key值,重複的不能儲存到字典中 NSDictionary *dy2 = @{@"we":@"haha", @"w":@"ha"}; NSLog(@"%lu",dy2.count); // 字典的遍曆 for (NSString *key in dy2) { NSLog(@"key = %@, value = %@", key, [dy2 objectForKey:key]); } // 枚舉類型遍曆 [dy1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"key = %@, value = %@", key, obj); }];
把字典存到檔案中
// 把字典儲存到檔案中 NSDictionary *dy2 = @{@"we":@"haha", @"w":@"ha"}; BOOL isWrite = [dy2 writeToFile:@"/Users/cloudwalk/Desktop/test.plist" atomically:YES]; if (isWrite) { NSLog(@"寫入成功"); }
從檔案中讀取字典
NSDictionary *readDy2 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/cloudwalk/Desktop/test.plist"]; NSLog(@"%@",readDy2);
通過把數組添加到字典中,構建成數組字典
NSArray *sdArr = [NSArray arrayWithObjects:@"zaozhuang",@"jinan",nil]; NSArray *jxArr = [NSArray arrayWithObjects:@"jiujiang",@"nanchang",nil]; NSDictionary *citys = [NSDictionary dictionaryWithObjectsAndKeys:sdArr,@"sd",jxArr,@"jx", nil]; NSLog(@"citys = %@",citys);
NSDictionary *citys = [NSDictionary dictionaryWithObjectsAndKeys:sdArr,@"sd",jxArr,@"jx", nil]; NSLog(@"citys = %@",citys); // 把citys存到檔案中 [citys writeToFile:@"/Users/cloudwalk/Desktop/test1.plist" atomically:YES];
Objective-C( Foundation架構 一 NSDictionary)