// // main.m // nsDictionary // // Created by syrcfwzx on 16/1/8. // Copyright (c) 2016年 syrcfwzx. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //注意key 通常是字符串对象 NSMutableDictionary* dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"jay",@"name",@"22",@"age",@"f",@"gender", nil]; NSLog(@"%@",dic); NSDictionary* dic1 = [NSDictionary dictionaryWithObject:@"166" forKey:@"height"]; [dic addEntriesFromDictionary:dic1]; NSLog(@"%@",dic); [dic setObject:@"66" forKey:@"weight"]; NSLog(@"%@",dic); //遍历 //1.先找到所有的key 2计算key的个数 NSArray* array = [dic allKeys]; NSInteger count = [dic count]; for(int i = 0;i<count;i++) { id key = [array objectAtIndex:i]; NSLog(@"%@",[dic objectForKey:key]); } //for in语法 for(id key in array) { id obj=[dic objectForKey:key]; NSLog(@"%@",obj); } //block遍历 [dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"key=%@ obj=%@",key,obj); }]; //3通过枚举对象进行枚举 //将字典里的key转成枚举对象 用于遍历 NSEnumerator* enumerator = [dic keyEnumerator]; id key; while (key=[enumerator nextObject]) { id obj3 = [dic objectForKey:key]; NSLog(@"%@",obj3); } } return 0; }
//课上实例
// // main.m // dictionary-01 // // Created by syrcfwzx on 16/1/7. // Copyright (c) 2016年 syrcfwzx. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //key一般为nsstring NSDictionary* dic = [NSDictionary dictionaryWithObject:@1 forKey:@"1"]; NSDictionary* dic2 = @{@"1":@1,@"2":@2}; NSDictionary* dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@1,@"1",@2,@"2",@3,@"3", nil]; NSArray* array = @[@1,@2,@3]; NSArray* array2 = @[@"1",@"2",@"3"]; NSDictionary* dic4 = [NSDictionary dictionaryWithObjects:array forKeys:array2]; //字典对象的使用 //通过key遍历 for(id key in dic3) { id obj = [dic3 objectForKey:key]; NSLog(@"%@",obj); } NSDictionary* concent = @{@"name":@"Tom", @"age":@25, @"tel":@"13888888888", @"email":@"tom@qq.com" }; NSDictionary* concent2 = @{@"name":@"Jerry", @"age":@23, @"tel":@"13884888888", @"email":@"jerry@qq.com" }; NSMutableArray* contactBook = [[NSMutableArray alloc]init]; [contactBook addObject:concent]; [contactBook addObject:concent2]; NSLog(@"%@",contactBook); //在字典对象中 key值必须是唯一的 不能重复 NSDictionary* concent3 = @{@"name":@"kobe", @"name":@"by", @"age":@27, @"tel":@"13884886888", @"email":@"kobe@qq.com" }; NSLog(@"%@",concent3); //字典对象的BLOCK遍历 [concent3 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"key=%@ : obj=%@",key,obj); }]; //字典对象写到文件中 //通过读文件写进字典 NSMutableDictionary* mutableDic = [[NSMutableDictionary alloc]init]; [mutableDic setDictionary:concent3]; [mutableDic removeObjectForKey:@"emial"]; [mutableDic removeObjectsForKeys:@[@"age",@"tel"]]; [mutableDic setObject:@30 forKey:@"age"]; NSLog(@"%@",mutableDic); } return 0; }