字典是以键值对的形式来存储数据 key value
字典的顺序不是自然顺序
NSArray * array = @[@"one",@"two"]; NSDictionary * dic3 = @{ @"one":@"1", @"num":[NSNumber numberWithInt:10], @"aaa":dic2, @"bbb":dic, @"ar1":array }; NSLog(@"dic3 %@",dic3); 016-08-14 14:44:17.461 07-字典类[2325:547877] dic3 { aaa = { one = 1; two = 2; }; ar1 = ( one, two ); bbb = { name = xiaozhe; }; num = 10; one = 1; }取出所有的key值
NSArray * allkeys = [dic3 allKeys]; NSLog(@"allkeys %@",allkeys); for (int i = 0; i < allkeys.count; i++) { NSString * key = [allkeys objectAtIndex:i]; //如果你的字典中存储的多种不同的类型,那么最好用id类型去接受它 id obj = [dic3 objectForKey:key]; NSLog(@"obj %@",obj); }枚举器
NSEnumerator * enumerator = [dic3 objectEnumerator]; id value; while (value = [enumerator nextObject]) { NSLog(@"value %@",value); }给一个 Student 类
@interface Student : NSObject @property (nonatomic,assign) int age; @property (nonatomic,strong) NSString * name; - (id)initWithName:(NSString *)name andAge:(int)age; @end @implementation Student - (id)initWithName:(NSString *)name andAge:(int)age { if (self = [super init]) { _name = name; _age = age; } return self; } - (NSString *)description { return [NSString stringWithFormat:@"name %@ age %d",_name,_age]; } @end Student * stu1 = [[Student alloc] initWithName:@"xiaoher" andAge:20]; Student * stu2 = [[Student alloc] initWithName:@"alex" andAge:50]; Student * stu3 = [[Student alloc] initWithName:@"xiaoli" andAge:10]; [muDic setObject:stu1 forKey:@"s1"]; [muDic setObject:stu2 forKey:@"s2"]; [muDic setObject:stu3 forKey:@"s3"]; //在向字典中存储数据的时候,一定要保证key值是唯一的 //[muDic setObject:stu3 forKey:@"s3"]; //[muDic setObject:stu3 forKey:@"s3"]; //[muDic setObject:stu3 forKey:@"s3"];新博客文章地址:NSDictionary字典创建,获取,遍历,可变字典的删除