黑马程序员技术交流社区

标题: OC的字典类 [打印本页]

作者: itheimaXYP    时间: 2014-8-19 19:29
标题: OC的字典类
本帖最后由 itheimaXYP 于 2014-8-19 19:32 编辑

NSDictionary、NSMutableDictionary 以键值对形式保存,键唯一且无序。


1、创建

[objc] view plaincopy
// NSDictionary  
NSDictionary *dict = @{"Android":"Google", "iOS":"Apple"};  
  
// NSMutableDictionary  
NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithCapacity:5];  

2、添加元素
[objc] view plaincopy
[mdict setObject: @"Oracle" forKey: @"Java"];  

3、删除元素
[objc] view plaincopy
[mdict removeObjectForKey: @"Java"]  

4、获取元素
[objc] view plaincopy
NSString *str = dict[@"iOS"];  
5、遍历
[objc] view plaincopy
// 方式一  
NSArray *keys = [dict allKeys];  
int count = [keys count];  
for (i = 0; i < count; i++)  
{  
    key = [keys objectAtIndex: i];  
    value = dict[key];  
    NSLog (@"Key: %@ Value: %@", key, value);  
}  
  
// 方式二  
NSArray *keys=[dict allKeys];  
for(id key in keys){  
    id value = dict[key];  
    NSLog (@"Key: %@ Value: %@", key, value);  
}  
  
// 方式三  
[dict enumerateKeysAndObjectsUsingBlock:^(id key,id value,BOOL *stop){  
    NSLog (@"Key: %@ Value: %@", key, value);  
}];  
作者: 南国    时间: 2014-8-19 21:02
刚好也不会




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2