字典 存储的内存不是连续的,用key和value进行对应(键值对) kvc 键值编码. 特点:取出的 key value 是无序的
//单元素字典 value key
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"1" forKey :@"a"];
NSLog(@"dict1 =%@",dict1);
-----------------------------------------------------------------------------------------------------------------
//多元素字典 value key
NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",nil] forKeys:[NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",nil]];
NSLog(@"dict2 =%@",dict2);
-----------------------------------------------------------------------------------------------------------------
//简便写法 key value
NSDictionary *dict3 = @{@"1":@"刘备",@"2":@"关羽",@"3":@"张飞"};
NSLog(@"dict3 = %@",dict3);
-----------------------------------------------------------------------------------------------------------------
//取字典长度
int count2 = (int)[dict2count];
NSLog(@"count2 =%d",count2);
-----------------------------------------------------------------------------------------------------------------
//通过 key 取value
NSString*value = [dict2valueForKey:@"a"];
NSLog(@"value =%@",value);
-----------------------------------------------------------------------------------------------------------------
//通过value 取key
NSString*value2 = [dict2objectForKey:@"d"];
NSLog(@"value2= %@",value2);
-----------------------------------------------------------------------------------------------------------------
//取字典中所有值
NSArray*dictValue = [dict2allValues];
NSLog(@"dictValue =%@",dictValue);
-----------------------------------------------------------------------------------------------------------------
//取字典中所有key
NSArray*dictKey = [dict2allKeys];
NSLog(@"dictKey =%@",dictKey);
-----------------------------------------------------------------------------------------------------------------
//取出数组中key对应的value ,如果没找到对应的value 则使用默认值
NSArray *dictKey2 = [dict2 objectsForKeys:[NSArray arrayWithObjects:@"a",@"b",@"z",nil] notFoundMarker:@"not fount"];
NSLog(@"dictKey2 =%@",dictKey2);
-----------------------------------------------------------------------------------------------------------------
//迭代器
NSEnumerator*enumerator = [dict2keyEnumerator];
idkey =nil;
while(key = [enumeratornextObject]) {
NSLog(@"enumeratot key =%@",key);
}
-----------------------------------------------------------------------------------------------------------------
//block 方式
[dict2enumerateKeysAndObjectsUsingBlock:^(id _Nonnullkey,id _Nonnullobj,BOOL*_Nonnullstop) {
}];
-----------------------------------------------------------------------------------------------------------------
网友评论