OC 学习笔记 - NSDictionary和NSMutableDictionary

NSDictionary和NSMutableDictionary

NSDictionary以键值对的形式存储数据,唯一的key对应value,通过key来找到存储在字典中的value。NSDictionary字典一旦创建完毕,其键值对的个数就已经固定,无法删除,新增。NSMutableDictionary是可变字典,相对于字典,可以进行键值对的删除和新增。

所属类 属性和方法 解释
NSDictionary count 获取字典中键值对的个数
NSDictionary allKeys 获取所有的key
NSDictionary allValues 获取所有value
NSDictionary -(nullable ObjectType)objectForKey:(KeyType)aKey 获取键对应的值
NSMutableDictionary -(void)removeObjectForKey:(KeyType)aKey 删除key对应的键值对
NSMutableDictionary -(void)setObject:(ObjectType)anObject forKey:(KeyType )aKey 添加键值对
NSMutableDictionary -(void)removeAllObjects 删除所有的键值对
NSMutableDictionary -(void)removeObjectsForKeys:(NSArray *)keyArray 删除数组中所有key的键值对

初始化

	NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:@"zj",@"name",@"19",@"age", nil];
	NSDictionary *dict1 = @{@"name":@"zj",@"age":@"19"};

遍历

    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSLog(@"%@:%@",key,obj);
    }];
    
	NSArray *keys= [dic allKeys];
    for (id obj in keys){
        NSLog(@"%@ => %@",obj,[dictionay objectForKey:obj]);
    }

你可能感兴趣的:(Objective-c)