main.m
//
// main.m
// NSDictionary
//
// Created by zhaogang on 16/5/8.
// Copyright ? 2016年 zhaogang. All rights reserved.
//
/*
集合
NSArray ArrayList
NSSet HashSet
NSDictionary Map
1. NSArray\NSMutableArray
* 有序
* 快速创建(不可变): @[]
* 快速访问元素: 数组名[]
2. NSSet\NSMutableSet
*无序
3. NSDictionary\NSMutableDictionary
* 无序
* 快速创建(不可变): @{key : value}
* 快速访问: 字典名[key]
*/
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSArray *person = @[
@{@"address" : @"beijing" , @"name" : @"jack", @"age" : @"22"},
@{@"address" : @"shanghai" , @"name" : @"rose", @"age" : @"21"},
@{@"address" : @"nanjing" , @"name" : @"mike", @"age" : @"23"},
@{@"address" : @"hongkong" , @"name" : @"hobe", @"age" : @"25"}
];
// NSDictionary *jack = person[0];
// NSLog(@"%@", jack);
NSLog(@"%@", person[1][@"address"]);
return 0;
}
void test3()
{
//字典不允许有想用的key,但允许有相同的value(object)
NSDictionary *dict = @{@"address" : @"beijing" , @"name" : @"jack", @"age" : @"22"};
// NSArray *keys = [dict allKeys];
// for(int i = 0; i < dict.count; i++)
// {
// //[keys objectAtIndex:i];
// NSString *key = keys[i];
// NSString *object = dict[key];
//
// NSLog(@"%@ - %@", key , object);
// }
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"%@ - %@" , key , obj);
//*stop = YES;
}];
}
void test2()
{
//错误
// NSMutableDictionary *dict = @{@"name" : @"jack"};
//
// [dict setObject:@"rose" forKey:@"name"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//添加键值对,没有顺序
[dict setObject:@"jack" forKey:@"name"];
[dict setObject:@"beijing" forKey:@"address"];
//这里会将上面的key的值覆盖
[dict setObject:@"rose" forKey:@"name"];
//移除键值对
//[dict removeObjectForKey:<#(nonnull id)#>];
NSString *str = dict[@"name"];
NSLog(@"%@",str);
//NSLog(@"%@", @[@"jack", @"rose"]);
NSLog(@"%@", dict);
}
void test()
{
/*
字典:
key---->value
索引---->文字内容
里面存储的东西都是键值对
*/
//NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"];
// NSArray *key = @[@"name", @"address"];
// NSArray *object = @[@"jack", @"beijing"];
//
// NSDictionary *dict = [NSDictionary dictionaryWithObjects:object forKeys:key];
// NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
// @"jack",@"name",
// @"beijing",@"address",
// @"22",@"age",nil];
NSDictionary *dict = @{@"name" : @"jack" , @"address" : @"beijing" , @"age" : @"22"};
id obj = [dict objectForKey:@"age"];
NSLog(@"%@", obj);
//返回键值队的个数
NSLog(@"%ld" , dict.count);
}
时间: 2024-10-25 13:02:50