字典
1.字典(dictionary)是由键-对象对组成的数据集合。在与字典中超找单词定义一样,可以通过对象的键从Objective-C字典中获取需要的值(即那个对象)。字典中的键必须是单值的,通常他们是字符串,但也可以是其他对象类型。和键关联的值可以是任意对象类型,但不能是nil。
2.练习代码
//1.dictionary 创建一个空字典 NSDictionary *dictionary = [NSDictionary dictionary]; //2.创建并初始化 // dictionaryWithObject:(id)forkey:(id)nscopying> NSDictionary *dictionary1 = [NSDictionary dictionaryWithObject:@"IOS" forKey:@"Android"]; NSLog(@"%@", dic1); //3.创建并返回一个字典。 // dictionaryWithObjects:forkeys NSArray * keys = [NSArray arrayWithObjects:@"name", @"sex", @"age", nil]; NSArray * values = [NSArray arrayWithObjects:@"Apple", @"Android", [NSNumber numberWithInt:25], nil]; NSDictionary * dictionary3 = [NSDictionary dictionaryWithObjects:values forKeys:keys]; NSLog(@"%@", dictionary3); //4.使用键-对象对{key1,obj1}、{key2,obj2}...创建词典 // dictionaryWithObjectsAndKeys NSDictionary * dictionary4 = [NSDictionary dictionaryWithObjectsAndKeys: @"IOS", @"name", @25, @"age", nil]; NSLog(@"%@", dictionary4);//5.allkeys 返回一个数组包含词典中所有的键 NSLog(@"allkeys:%@", [dictionary5 allKeys]); //6.allkeysForObject: 返回一个数组,包含所有对应到给定对象的关键字。 NSArray * aa = @[@"name",@"IOS",@"WinPhone",@"Android"]; NSLog(@"aaaaaaa%@", [dictionary5 allKeysForObject:aa]); //7.allValues:返回一个数组包含词典中所有的值 NSLog(@"allValues:%@", [dictionary5 allValues]); //8.objectForKey:返回指定 key 的 value,若没有这个 key 返回 nil. NSLog(@"%@", [dictionary5 objectForKey:@"name"]); //9.valueForKey 同样是返回指定 key 的 value。 NSLog(@"%@", [dictionary5 valueForKey:@"name"]);//10.count:返回字典中的记录数 NSLog(@"count:%zi", [dictionary5 count]); //11.遍历字典中的key NSLog(@"遍历字典\n\n");//快速遍历 for (id key in dictionary5) { NSLog(@"%@", key); } //遍历字典中的value for (id key in dictionary5) { NSLog(@"%@", [dictionary5 valueForKey:key]); }//12.可变字典 NSMutableDictionary * dictionary2 = [NSMutableDictionary dictionary]; //13.setObject: forKey: 添加value与key,如果key存在则替换该值 [dictionary2 setValue:@"itheima" forKey:@"first"]; [dictionary2 setValue:@"itcast" forKey:@"second"]; NSLog(@"%@", dictionary2); //14.removeObjectForKey 删除词典中指定key对应的记录 [dic2 removeObjectForKey:@"100"]; NSLog(@"%@", dictionary2); //15.removeAllObjects 删除词典中的所有记录 [dic2 removeAllObjects]; NSLog(@"%@", dictionary2); NSDictionary * diction1 = [NSDictionary dictionaryWithObjectsAndKeys: @"IOS", @"Name", @15, @"Age",nil]; NSDictionary * diction2 = [NSDictionary dictionaryWithObjectsAndKeys: @"Android", @"Name", @28, @"Age",nil]; //16.isEqualToDictionary 比较两个字典 if([diction1 isEqualToDictionary:diction2]){ NSLog(@"diction1 equal diction2"); }else{ NSLog(@"diction1 not equal diction2"); } //17.writeToFile 把字典写入文件(xml格式) NSString * path = @"/Users/caile/diction1.xml"; [diction1 writeToFile:path atomically:YES]; //18.dictionaryWithContentsOfFile 读取一个文件返回给新的字典对象 NSDictionary *newDic = [NSDictionary dictionaryWithContentsOfFile:path];
时间: 2024-10-13 22:18:59