字典是OC中一种特殊的类型,功能非常强大。是Foundation中的重要组成部分。我们来学习一下:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
/*
字典:
1.存储的内存不是连续的;
2.用key和value进行对应(键值);
3.KVC:键值编码;
*/
//创建方式1;
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"];
NSLog(@"%@",dict);
//创建方式2:
NSArray *arrValue = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil];
NSArray *arrKeys = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d", nil];
NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:arrValue forKeys:arrKeys];
NSLog(@"%@",dict1);
//创建方式3:简便创建方式;
//@{} ;表示字典;!!!!!
NSDictionary *dict3 = @{@"1":@"a",@"2":@"b"};
NSLog(@"%@",dict3);
//长度:
int count = (int)dict3.count;
NSLog(@"count = %d",count);
//根据键获取值
NSString *str = [dict3 objectForKey:@"2"];
NSLog(@"键值 = %@",str);
//也可以使用下面的方法:
NSString *str2 = [dict3 valueForKey:@"2"];
NSLog(@"键值 = %@",str2);
//获取字典中的所有值;(value)
NSArray *arr5 = [[NSArray alloc] initWithObjects:@"1",@"2", @"3",nil];
NSArray *arrAllValue = [dict3 objectsForKeys:arr5 notFoundMarker:@"none"];
NSLog(@"所有值方法1 = %@",arrAllValue);
//还有一种获取所有值的方法;
NSArray *arrAllValue2 = [dict3 allValues];
NSLog(@"所有值方法2 = %@",arrAllValue2);
//获取字典中的所有键;(key)
NSArray *arrAllKey = [dict3 allKeys];
NSLog(@"所有键 = %@",arrAllKey);
//遍历数组;
//需要使用键去遍历;
for (NSString *key in dict3) {
NSString *value = [dict3 objectForKey:key];
NSLog(@"key = %@,value = %@",key,value);
}
//使用迭代器进行遍历;
NSEnumerator *en = [dict3 keyEnumerator];
id key = nil;
while (key = [en nextObject]) {
NSString *str = [dict3 objectForKey:key];
NSLog(@"迭代器获取值 = %@",str);
}
}
return 0;
}
输出结果如下:
.
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!