API之NSDictionary的常见用法

/*

NSDictionary *dic1 = [[NSDictionary alloc]

initWithObjectsAndKeys:@"李四", @"name", @"不明",@"gender", nil];


//字典中的对象可以重复存储

//71 - (instancetype)initWithObjectsAndKeys:(id)firstObject, ...

NSDictionary *dic2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"大圣", @"name", @"大圣",@"monkey", @"八戒", @"贪吃", nil];

// NSLog(@"%@", [dic1objectForKey:@"name"]);

// NSLog(@"%@", dic1); //打印UTF8编码一个UTF8是两个字节


// //把所有key作为数组输出

// NSArray *keys = [dic1 allKeys];

//

// for (int i = 0; i < [keys count]; i++) {

// NSLog(@"%@ : %@", keys[i], dic1[keys[i]]);

// }


// //输出同一对象的所有下标

// NSLog(@"%@", [dic2allKeysForObject:@"sun"]);


// //获取字典里所有元素

// NSArray *array1 = [dic1 allValues];

// NSLog(@"%@", array1);


// //判断两个数组是否相等

// if ([dic1 isEqualToDictionary:dic2]) {

// NSLog(@"yes");

// } else {

// NSLog(@"no");

// }

*/



/*

//72 - (instancetype)initWithDictionary:

(NSDictionary *)otherDictionary;

NSDictionary *dic3 = [[NSDictionary alloc]

initWithDictionary:dic2];

NSLog(@"%@", dic3);


//87 - (void)removeObjectForKey:(id)aKey;

NSArray *key2 = [dic2 allKeys];

*/


//可变字典

NSMutableDictionary *mDic1=

[[NSMutableDictionaryallocinitWithObjectsAndKeys:@"多啦A",@"name", @"百变", @"skill", nil];

NSArray *keys1= [mDic1 allKeys];

for (int i = 0; i <[keys1 count]; i++) {

NSLog(@"%@ : %@", [keys1objectAtIndex:i],

[mDic1 objectForKey:[keys1 objectAtIndex:i]]);

}


//通过key移除对象

// [mDic1 removeObjectForKey:@"name"];

// NSLog(@"%@", [mDic1objectForKey:@"name"]);

NSMutableDictionary *mDic2=[[NSMutableDictionaryalloc]init];


//把后面的字典拷⻉贝给前面的字典

[mDic2 setDictionary:mDic1];

// NSArray *key2 = [mDic2 allKeys];

// for (int i = 0; i < [key2 count]; i++) {

// NSLog(@"%@ : %@", [key2 objectAtIndex:i],

[mDic2 objectForKey:[key2 objectAtIndex:i]]);

// }


//重新写key所保存的对象

[mDic2 setObject:@"大熊"forKey:@"name"];

NSArray *key2= [mDic2 allKeys];

for (int i = 0; i< [key2 count]; i++) {

NSLog(@"%@ : %@", [key2objectAtIndex:i],

[mDic2 objectForKey:[key2 objectAtIndex:i]]);

}

//88 - (void)setObject:(id)anObject forKey:(id

)aKey; 空指针相当于上面的代

你可能感兴趣的:(API之NSDictionary的常见用法)