/*
字典:
存储的内存不是连续的,
key-value 对应,
*/
// 创建方法:
// 1.不常用,只有一组k-v
NSDictionary* dict1 = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"];
NSLog(@"dict1 = %@", dict1);
// 2. 创建多个
NSDictionary* dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"2",@"3", nil] forKeys:[NSArray arrayWithObjects:@"a", @"b", @"c", nil]];
NSLog(@"dict2 = %@", dict2);
// 3. ios5以后的简便写法
NSDictionary* dict3 = @{@"a":@"1", @"b":@"2"};
NSLog(@"dict3 = %@", dict3);
// 常用方法
// count
int count = [dict2 count];
NSLog(@"count = %d", count);
// key, value查找
NSString* value = [dict2 valueForKey:@"b"];
NSLog(@"value for b is %@", value);
NSString* value2 = [dict2 objectForKey:@"b"];
NSLog(@"value2 for b is %@", value2);
NSArray* allValues = [dict2 allValues];
NSLog(@"all values is %@", allValues);
NSArray* allKeys= [dict2 allKeys];
NSLog(@"all keys are is %@", allKeys);
NSArray* array = [dict2 objectsForKeys:[NSArray arrayWithObjects:@"a", @"b", @"d", nil] notFoundMarker:@"Not Found"];
NSLog(@"array is %@", array);
//遍历字典
// for in 快速遍历
for(NSString* str in dict2){
NSLog(@"the key is %@, the value is %@", str, dict2[str]);
}
//2. 枚举器遍历
NSEnumerator* en = [dict2 keyEnumerator];
id key = nil;
while(key = [en nextObject]){
NSLog(@"key - %@", key);
}
//NSMutableDictionary
// 1. 添加
NSMutableDictionary* dict4 = [[NSMutableDictionary alloc] init]; // 不需要初始赋值,因为可以随时添加
[dict4 setObject:@"1" forKey:@"a"];
[dict4 setObject:@"2" forKey:@"b"];
[dict4 setObject:@"3" forKey:@"c"];
[dict4 setObject:@"4" forKey:@"d"];
// 2. 删除
[dict4 removeObjectForKey:@"a"];
[dict4 removeObjectsForKeys: [NSArray arrayWithObjects:@"a",@"b", nil]];
[dict4 removeAllObjects];
iOS 学习笔记4-NSDictionary 和 NSMutableDictionary
最新推荐文章于 2020-09-26 19:22:06 发布