Objective-C 字典、可变字典

字典相当于c++ stl中的map

字典NSDictionary

 1 #import <UIKit/UIKit.h>
 2 #import "AppDelegate.h"
 3 
 4 int main(int argc, char * argv[]) {
 5     // 从@符号创建字典  实际上就是键值对容器
 6     NSDictionary *dict = @{@"name":@"zhangsan",@"sex":@"male"};
 7     NSLog(@"%@",dict);
 8     
 9     // 根据键获取值
10     NSLog(@"%@",[dict objectForKey:@"name"]);
11     
12     // 从配置文件中读取
13     NSDictionary *dict1 = [NSDictionary dictionaryWithContentsOfFile:
14         [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist" ]];
15     NSLog(@"%@",[dict1 objectForKey:@"name"]);
16     NSLog(@"%@",[dict1 objectForKey:@"age"]);
17     
18         @autoreleasepool {
19         return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
20     }
21 }

 

可变字典 NSMutableDictionary

1     NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
2     // setObject 可以新增key 也可以修改已有key的值
3     [dict2 setObject:@"jinpangpang" forKey:@"name"];
4     [dict2 setObject:@"113" forKey:@"name"];
5     NSLog(@"%@",[dict2 objectForKey:@"name"]);

 

posted @ 2015-11-27 19:47  金胖胖  阅读(358)  评论(0编辑  收藏  举报