iOS学习路之Objective-C(六)—— NSDictionary和NSMutableDictionary
-
创建一个不可变的字典
1 //字典中的元素是成对出现的,key-value,key(键,索引),value(值,索引对应的值),两者均是id对象 2 NSDictionary *dictionary = @{@"key":@"value", @"key2":@"value2"}; 3 #if 0 4 #pragma mark 对象方法 5 NSDictionary *dictionary1 = [[NSDictionary alloc] initWithDictionary:dictionary]; 6 NSDictionary *dictionary2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"key",@"value", @"key2", @"value2", nil]; 7 #endif 8 9 #pragma mark 类方法 10 NSDictionary *dictionary1 = [NSDictionary dictionaryWithDictionary:dictionary]; 11 NSDictionary *dictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:@"key",@"value", @"key2", @"value2", nil];
-
获取字典中元素的个数
1 NSDictionary *dictionary = @{@"key":@"value", @"key2":@"value2"}; 2 //@property (readonly) NSUInteger count; 3 //作用:获取字典键值对的个数 4 NSLog(@"%lu", [dictionary count]);
-
通过键找对应的值
1 NSDictionary *dictionary = @{@"key":@"value", @"key2":@"value2"}; 2 //- (id)objectForKey:(id)aKey; 3 //作用:通过键值寻找Value 4 NSString *string = [dictionary objectForKey:@"key"]; 5 NSLog(@"%@", string);
-
获取字典中所有的key
NSDictionary *dictionary = @{@"key":@"value", @"key2":@"value2"}; //@property (readonly, copy) NSArray *allKeys; //作用:获取字典中所有的key NSArray *array = [dictionary allKeys];
-
获取字典中所有的value
NSDictionary *dictionary = @{@"key":@"value", @"key2":@"value2"}; //@property (readonly, copy) NSArray *allValues; //作用:获取所有的Value NSArray *array = [dictionary allValues];
-
创建一个可变的字典
1 #pragma mark 对象方法 2 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:0]; 3 #pragma mark 类方法 4 NSMutableDictionary *dictionary1 = [NSMutableDictionary dictionaryWithCapacity:0];
-
向字典中追加键值对
1 NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:0]; 2 //- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey; 3 //作用:当key值在字典中已经存在,可以对键值对进行替换,如果不存在,就追加在字典尾部 4 [dictionary setObject:@"value" forKey:@"key"]; 5 [dictionary setObject:@"value2" forKey:@"key2"];
-
删除字典中的键值
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:0]; [dictionary setObject:@"chen chao" forKey:@"namel"]; [dictionary setObject:@"183" forKey:@"height"]; [dictionary setObject:@"shuai" forKey:@"info"]; //- (void)removeObjectForKey:(id)aKey; //作用:删除key对应的键值对 [dictionary removeObjectForKey:@"info"];
-
修改字典
NSDictionary *dic = @{@"key":@"value", @"key2":@"value2"}; NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:0]; [dictionary setObject:@"chen chao" forKey:@"namel"]; [dictionary setObject:@"183" forKey:@"height"]; [dictionary setObject:@"shuai" forKey:@"info"]; //- (void)setDictionary:(NSDictionary *)otherDictionary; //作用:将当前字典用另一个字典替换 [dictionary setDictionary:dic];
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。