//通过类对象创建字典
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:@[@1,@2,@3] forKeys:@[@"A",@"B",@"C"]];
//通过键取字典中值
NSLog(@"count:%lu,A:%@,B:%@,C:%@",
dic.count,
[dic objectForKey:@"A"],
[dic objectForKey:@"B"],
[dic objectForKey:@"C"]);
//一值一键,先值后键
NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@1,@"A",@2,@"B",@3,@"C",@4,@"D", nil];//value,key
//遍历值
for (id v in dic1.objectEnumerator) {
NSLog(@"%@",v);
}
//遍历键
for (id v in dic1.keyEnumerator) {
NSLog(@"%@",v);
}
//通过现有字典创建可扩展字典
NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:dic1];
//向可扩展字典中添加键值对
[mdic setObject:@5 forKey:@"E"];
//创建不可扩展字典
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:@[@6,@7,@8] forKeys:@[@"F",@"G",@"H"]];
//向可扩展字典中添加现有字典
[mdic addEntriesFromDictionary:dic2];
//遍历字典
for (id x in mdic) {
NSLog(@"%@",x);
}
//创建可扩展集合对象
NSMutableArray *numArray = [[NSMutableArray alloc] init];
//向集合添加数据
for (int i=0; i<100; i++) {
//创建数字对象
NSNumber *num1 = [[NSNumber alloc]initWithInt:i];
[numArray addObject:num1];
}
//正向遍历集合
for (id n in numArray.objectEnumerator) {
NSLog(@"%@",n);
}
//反向遍历集合
for (id n in numArray.reverseObjectEnumerator) {
NSLog(@"%@",n);
}
//大数使用NSDecimalNumber
[numArray removeAllObjects];
for (int i=1; i<101; i++) {
//创建数字对象
NSNumber *num1 = [[NSDecimalNumber alloc]initWithInt:i*999999];
[numArray addObject:num1];
}
//正向遍历集合
for (id n in numArray.objectEnumerator) {
NSLog(@"%@",n);
}
//反向遍历集合
for (id n in numArray.reverseObjectEnumerator) {
NSLog(@"%@",n);
}
Objective-C字典NSDictionary与可变字典NSMutableDictionary使用
原创
©著作权归作者所有:来自51CTO博客作者编程汇也的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
iOS开发OC基础:OC字典NSDictionary以及NSMutableDictionary基本方法的使用
本文介绍了OC中的字典的基本使用方法,大家可以了解一下。
iOS基础 OC字典 NSDiction