OC中的NSDictionary和NSMutableDictionary
作者:互联网
学习链接:https://www.cnblogs.com/-boy/archive/2004/01/13/4096453.html
// // learn_dic.m // learn_KVC // // Created by 蔡佳明 on 2020/10/15. // #import <Foundation/Foundation.h> int main() { //创建字典 必须初始化 并且创建之后不能再变了 // 没初始化 没意义 NSDictionary *dic=[NSDictionary dictionary]; //创建只有一个键值对的字典 NSDictionary *dic1=[NSDictionary dictionaryWithObject:@"yaoming" forKey:@"ym"]; //创建多个键值对字典 NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"liuxiang",@"lx",@"jiaming",@"jm", nil]; //快速创建方法 NSDictionary *dic3=@{@"ym":@"yaoming",@"lx":@"liuxiang"}; //字典访问 //返回字典中键值个数 NSUInteger len=dic3.count; NSLog(@"键值个数为:%lu",len); //根据键求值 //方式1 id str=[dic3 objectForKey:@"lx"]; //方式2 str=dic3[@"lx"]; NSLog(@"str=%@",str); //字典的遍历 //for循环 id key=[dic3 allKeys]; for(int i=0;i<dic3.count;i++) { str=dic3[key[i]]; NSLog(@"%@:%@",key[i],str); } //for in遍历 for(NSString *key in dic3) { str=dic3[key]; NSLog(@"%@:%@",key,str); } //下面说一下可变的的字典 //创建一个可变的空字典 NSMutableDictionary *dicM = [NSMutableDictionary dictionary]; [dicM setObject:@"zhangsan" forKey:@"zs"]; [dicM setObject:@"lisi" forKey:@"ls"]; for(NSString *key in dicM) { str=dicM[key]; NSLog(@"%@:%@",key,str); } //删除指定的键值对 [dicM removeObjectForKey:@"zs"]; for(NSString *key in dicM) { str=dicM[key]; NSLog(@"%@:%@",key,str); } //删除字典中所有的内容 [dicM removeAllObjects]; return 0; }
标签:OC,NSDictionary,NSMutableDictionary,dic3,键值,str,lx,字典 来源: https://www.cnblogs.com/caijiaming/p/13822180.html