本帖最后由 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);
}]; |