您的位置:首页 > 移动开发 > Objective-C

Object-C-NSDictionary

2015-06-08 10:56 483 查看
存储对象都必须是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:)];

字典:
//key 一般使用字符串
//value 可以使用任意对象类型
//        NSDictionary *scores = [[NSDictionary alloc]initWithObjectsAndKeys:@"89",@"english",@"70",@"computer", nil];
//
//        NSLog(@"%@",scores);

NSDictionary *scores2=[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:89],@"english",
[NSNumber numberWithInt:92],@"maths",
[NSNumber numberWithInt:70],@"computer"
, nil];

//        NSLog(@"%ld",[scores2 count]);
//        NSLog(@"%@",scores2);
NSNumber *englishScores = [scores2 objectForKey:@"english"];
NSLog(@"%@",englishScores);
NSLog(@"%d",[englishScores intValue]);
//        //遍历方法1:for in
for (NSString *key in scores2) {
//通过每个元素的key访问value
NSLog(@"%@:%d",key,[[scores2 objectForKey:key] intValue]);
}
//         //遍历方法2:for
NSArray *keysArray = [scores2 allKeys];
for (int i=0; i<[scores2 count]; i++) {
NSString *key = [keysArray objectAtIndex:i];
NSLog(@"%@:%d",key,[[scores2 objectForKey:key]intValue]);
}
//
//排序
NSArray *keys = [scores2 keysSortedByValueUsingSelector:@selector(compare:)];
NSLog(@"%@",keys);
}
return 0;


View Code
ie
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: