/*
集合
1.NSArray\NSMutableArray
•有序
•快速创建(不可变):@[obj1, obj2, obj3]
•快速访问元素:数组名[i]
2.NSSet\NSMutableSet
•无序
3.NSDictionary\NSMutableDictionary
•无序
•快速创建(不可变):@{key1 : value1, key2 : value2}
•快速访问元素:字典名[key]
*/
NSDictionary:字典
代码示例
1>
void create() { /* 字典: key ----> value 索引 ----> 文字内容 里面存储的东西都是键值对 */ // 字典创建方式 // NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"]; // NSArray *keys = @[@"name", @"address"]; // NSArray *objects = @[@"jack", @"北京"]; // NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; /* NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"jack", @"name", @"北京", @"address", @"32423434", @"qq", nil]; */ // 最实用的方法 NSDictionary *dict = @{@"name" : @"jack", @"address" : @"北京"}; // id obj = [dict objectForKey:@"name"]; // 获取值 id obj = dict[@"name"]; NSLog(@"%@", obj); // 返回的是键值对的个数 NSLog(@"%ld", dict.count); }
2> 基本使用
void use1() { NSMutableDictionary *dict = [NSMutableDictionary dictionary]; // 添加键值对 [dict setObject:@"jack" forKey:@"name"]; [dict setObject:@"北京" forKey:@"address"]; [dict setObject:@"rose" forKey:@"name"]; // 移除键值对 // [dict removeObjectForKey:<#(id)#>]; NSString *str = dict[@"name"]; //NSLog(@"%@", str); NSLog(@"%@", dict); //NSLog(@"%@", @[@"jack", @"rose"]); } void use2() { NSMutableDictionary *dict = @{@"name" : @"jack"}; [dict setObject:@"rose" forKey:@"name"]; } void use3() { // 字典不允许有相同的key,但允许有相同的value(Object) // 字典的无序的 NSDictionary *dict = @{ @"address" : @"北京", @"name" : @"jack", @"name2" : @"jack", @"name3" : @"jack", @"qq" : @"7657567765"}; // NSArray *keys = [dict allKeys]; // // for (int i = 0; i<dict.count; i++) // { // NSString *key = keys[i]; // NSString *object = dict[key]; // // // NSLog(@"%@ = %@", key, object); // } // 使用Block来访问 [dict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) { NSLog(@"%@ - %@", key, obj); // *stop = YES; }]; }
#import <Foundation/Foundation.h> int main() { NSArray *persons = @[ @{@"name" : @"jack", @"qq" : @"432423423", @"books": @[@"5分钟突破iOS编程", @"5分钟突破android编程"]}, @{@"name" : @"rose", @"qq" : @"767567"}, @{@"name" : @"jim", @"qq" : @"423423"}, @{@"name" : @"jake", @"qq" : @"123123213"} ]; // NSDictionary *jim = persons[2]; NSString *bookName = persons[0][@"books"][1]; NSLog(@"%@", bookName); //NSArray *array = persons[0][@"books"]; //NSLog(@"%@", array); // 先取出1位置对应的字典 // 再取出字典中qq这个key对应的数据 //NSLog(@"%@", persons[1][@"qq"]); // NSLog(@"%@", jim); return 0; }
代码是以前学习时照着李明杰老师的视频敲的,再次,向他表示感谢;李老师说的很好,推荐大家去看,他交的不是编程,而是一种思想,让我受益匪浅。