字典的练习和使用(遍历,搜索。。。)(Student和Book类文件可以查看上篇博客这次不上传了。)
// // main.m // NSDictionary // // Created by WildCat on 13-7-26. // Copyright (c) 2013年 wildcat. All rights reserved. // #pragma mark - NSDictionary练习 #import <Foundation/Foundation.h> #import "Student.h" #pragma mark 创建字典 void dictCreat(){ //第一种方式 NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; NSLog(@"The Dictionary is:%@",dict); //第二种方式 NSArray *objects=[NSArray arrayWithObjects:@"v1",@"v2",@"v3",@"v4", nil]; NSArray *keys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3",@"k4", nil]; dict=[NSDictionary dictionaryWithObjects:objects forKeys:keys]; NSLog(@"The Dictionary is:%@",dict); } #pragma mark 字典的使用 void dictUser(){ //创建一个字典 NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //由于NSDIctionary是不可变的,只能取值,不能修改值 id obj=[dict objectForKey:@"k2"];//查找值 NSLog(@"The obj is :%@",obj); NSInteger count=[dict count];//获得个数 NSLog(@"Count :%zi",count); //将字典写入文件中 NSString *path=@"/Users/bird/Desktop/dict.xml"; [dict writeToFile:path atomically:YES]; //通过keys获得values NSArray *objects=[dict objectsForKeys:[NSArray arrayWithObjects:@"k1",@"k2",@"k4", nil] notFoundMarker:@"not-finde"]; NSLog(@"object:%@",objects); } #pragma mark 遍历字典 void dictionaryFor(){ NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //第一种方法 for (id keys in dict) { id object=[dict objectForKey:keys]; NSLog(@"%@--%@",keys,object); } //第二种方法 通过迭代器遍历 NSEnumerator *keyenu=[dict keyEnumerator]; id key=nil; NSLog(@"迭代器遍历:"); while (key=[keyenu nextObject]) { id object=[dict objectForKey:key]; NSLog(@"%@--%@",key,object); } NSLog(@"通过BLock遍历:"); //第二种方法 通过Block遍历 [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"%@--%@",key,obj); }]; } #pragma mark 可变字典 void mutableDictUser(){ Student *stu1=[Student initWithFirstName:@"lele" LastName:@"li"]; Student *stu2=[Student initWithFirstName:@"ll" LastName:@"li"]; Student *stu3=[Student initWithFirstName:@"xingle" LastName:@"li"]; NSMutableDictionary *dict=[NSMutableDictionary dictionary]; [dict setValue:stu1 forKey:@"k1"]; [dict setValue:stu2 forKey:@"k2"]; [dict setValue:stu3 forKey:@"k3"]; NSLog(@"%@",dict); //删除所有元素 //[dict removeAllObjects]; //通过键值删除元素 [dict removeObjectForKey:@"k2"]; NSLog(@"%@",dict); } int main(int argc, const char * argv[]) { @autoreleasepool { //dictCreat(); //dictUser(); //dictionaryFor();//遍历字典 mutableDictUser(); } return 0; }
作者:superlele123 发表于2013-7-26 14:09:36 原文链接
阅读:0 评论:0 查看评论