存储对象都必须是id(对象类型)不能使基础类型
NSDictionary *scores=[[NSDictionary alloc]initWithObjectsAndKeys:@"89",@"english",@"70",@"computer",nil];
*scores=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:89],@"english"];
scores=[NSDictionary dictionaryWithObjectsAndKeys:]用法与initWithObjectsAndKeys;
NSNumber *englishScore=[scores objectForKey:@"english"];
集合的遍历
方法一
for(NSString *key int socres)
{
// 通过每个元素的key访问value
NSLog(@"%@:%d",key,[[score objetForKey:key] intValue]);
}
方法二
[socres enumerateKeysAndObjectsUsingBloc:^(id key, id obj,BOOL *stop)
{
NSNumber *num=(NSNumber *)obj;
NSLog(@"%@:%d",key,[num intValue]);
}
方法三
NSArray *keysArray = [scores allKeys];
for(int i=0; i<[scores count]; i++)
{
NSLog(@"%@:%d",[keysArray objectAtIndex:i);
NSLog(@"")----;
}
字典排序
NSArray *keysArray=[scores keysSortedByValueUsingSelector:@selector(compare:)];
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 字典: 2 //key 一般使用字符串 3 //value 可以使用任意对象类型 4 // NSDictionary *scores = [[NSDictionary alloc]initWithObjectsAndKeys:@"89",@"english",@"70",@"computer", nil]; 5 // 6 // NSLog(@"%@",scores); 7 8 NSDictionary *scores2=[NSDictionary dictionaryWithObjectsAndKeys: 9 [NSNumber numberWithInt:89],@"english", 10 [NSNumber numberWithInt:92],@"maths", 11 [NSNumber numberWithInt:70],@"computer" 12 , nil]; 13 14 // NSLog(@"%ld",[scores2 count]); 15 // NSLog(@"%@",scores2); 16 NSNumber *englishScores = [scores2 objectForKey:@"english"]; 17 NSLog(@"%@",englishScores); 18 NSLog(@"%d",[englishScores intValue]); 19 // //遍历方法1:for in 20 for (NSString *key in scores2) { 21 //通过每个元素的key访问value 22 NSLog(@"%@:%d",key,[[scores2 objectForKey:key] intValue]); 23 } 24 // //遍历方法2:for 25 NSArray *keysArray = [scores2 allKeys]; 26 for (int i=0; i<[scores2 count]; i++) { 27 NSString *key = [keysArray objectAtIndex:i]; 28 NSLog(@"%@:%d",key,[[scores2 objectForKey:key]intValue]); 29 } 30 // 31 //排序 32 NSArray *keys = [scores2 keysSortedByValueUsingSelector:@selector(compare:)]; 33 NSLog(@"%@",keys); 34 } 35 return 0;
ie