黑马程序员技术交流社区
标题:
NSDictionary
[打印本页]
作者:
苏子瞻201068
时间:
2015-9-19 10:45
标题:
NSDictionary
1、字典NSDictionary
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"
one
"
,
@"
1
"
,
@"
two
"
,
@"
2
"
,
@"
three
"
,
@"
3
"
, nil];
字典中的元素是以键值对的形式存储的
@"one"和@"1"组成了一个键值对
@"one"称为值(value)@"1"称为键(key)
键值对的键和值,都是任意的对象,但是键往往使用字符串
字典存储对象的地址没有顺序
2、字典的遍历分为:键的遍历和值的遍历
NSEnumerator *enumeratorKey = [dict keyEnumerator];
//
键的遍历
NSEnumerator *enumeratorValue = [dict objectEnumerator];
//
值的遍历
3、通过键快速的找到值
NSString *str = [dict objectForKey:
@"
1
"
];
快速枚举法
for
(
id
obj
in
dict){
//
这种方式遍历到的是键Key,获得了键,也就获得了值
NSLog(
@"
%@
"
,obj);
NSLog(
@"
%@
"
,[dict objectForKey:obj]);
}
4
、可变字典NSMutableDictionary
//
初始化
NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
添加键值对(set……)
//
添加
[mDict setObject:
@"
one
"
forKey:
@"
1
"
];
[mDict setObject:
@"
two
"
forKey:
@"
2
"
];
删除键值对(remove……)
//
删除
[mDict removeObjectForKey:
@"
1
"
];
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2