#import <Foundation/Foundation.h>
#pragma mark 字典相关
void dict(){
// 创建一个字典
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
nil];
NSArray *values = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSDictionary *dict3 = [NSDictionary dictionaryWithObjects:values forKeys:keys];
NSLog(@"%@", dict1);
NSLog(@"%@", dict2);
NSLog(@"%@", dict3);
}
#pragma mark 字典的用法
void dict2(){
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
nil];
// 统计字典中的键值对
NSUInteger num = [dict1 count];
NSLog(@"%ld", num);
// 获取字典中的值
id obj = [dict1 objectForKey:@"key2"];
NSLog(@"%@", obj);
}
#pragma mark 字典的遍历
void dict3(){
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
nil];
// for in遍历
for (id key in dict1) {
id value = [dict1 objectForKey:key];
NSLog(@"For:%@->%@", key, value);
}
// 迭代器遍历
[dict1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"Block:%@->%@", key, obj);
}];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
dict3();
}
return 0;
}
【OC】字典
最新推荐文章于 2019-09-10 16:26:32 发布