NSDictionary用法
使用
// NSDictionary
-(void)testNSDictionary{
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1", @"value2", @"key2", nil];
//得到词典的数量
NSUInteger _count = [dictionary count];
NSLog(@"词典的数量为:%lu", (unsigned long)_count);
//得到词典中所有KEY值
NSEnumerator * enumeratorKey = [dictionary keyEnumerator];
//快速美剧遍历所有KEY值
for(NSObject *object in enumeratorKey) {
NSLog(@"遍历KEY的值:%@", object);
}
//得到词典中所有value值
NSEnumerator * enumberatorValue = [dictionary objectEnumerator];
//得到词典中d所有value值
for(NSObject *object in enumberatorValue) {
NSLog(@"遍历Value值:%@", object);
}
//通过KEY找到value
NSObject *object = [dictionary objectForKey:@"key1"];
if(object != nil) {
NSLog(@"通过KEYd找到的value是:%@", object);
}
}
结果
词典的数量为:2
遍历KEY的值:key1
遍历KEY的值:key2
遍历Value值:value1
遍历Value值:value2
通过KEYd找到的value是:value1
NSMutableDictionary
使用
// NSMutableDictionary
-(void)testNSMutableDictionary{
//创建词典对象,初始化长度10
NSMutableDictionary *dictinary = [NSMutableDictionary dictionaryWithCapacity:10];
//向词典中动态添加数据
[dictinary setObject:@"value1" forKey:@"key1"];
[dictinary setObject:@"value2" forKey:@"key2"];
//通过KEY找到value
NSObject *object = [dictinary objectForKey:@"key1"];
if(object != nil) {
NSLog(@"通过KEY找到的value是:%@", object);
}
}
结果
通过KEY找到的value是:value1