现在每天要抓紧的学习了,所以争取每天能学习两个知识点,尽快把OC学习完,然后进入开发阶段! 加油.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
#pragma mark - NSDictionary
//NSDictionary
//使用initWithObjectsAndKeys:方法创建字典对象
//在对象创建过程中,一次性存入多个键值对,值(value)在前,键(keys)在后,键值之间用,号隔开,最后以nil结尾
//字典和数组不一样,字典的内部元素是无序的内部都是由一个个条目(键值对)组成的,所以是没有顺序的.
NSDictionary *obj1= [[NSDictionary alloc] initWithObjectsAndKeys:@"Jack",@"name",@"male",@"sex",[NSNumber numberWithInt:28],@"age", nil];
//通过key值获取value
NSLog(@"=======通过key获取value======");
NSString *sex = [obj1 valueForKey:@"sex"];
NSLog(@"%@",sex);
//获取所有value
NSLog(@"=======allValue======");
NSArray *allObjectValue = [obj1 allValues];
NSLog(@"%@",allObjectValue);
//获取所有key
NSLog(@"=======allkeys=======");
NSArray *allObjectKey = [obj1 allKeys];
NSLog(@"%@",allObjectKey);
//便利字典 便利只能便利key,然后在通过key找value
NSLog(@"=====便利=========");
for (NSString *key in obj1) {
NSLog(@"%@",[obj1 valueForKey:key]);
}
#pragma mark - NSMutableDictionary
//NSMutableDictionary
//使用便利构造器,创建可变字典对象
NSLog(@"=======1========");
NSMutableDictionary *obj2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Henry",@"name",@"male",@"sex",@"26",@"age", nil];
NSLog(@"%@",obj2);
//字典有两个方法来添加:
//1.通常情况下都是用setValue forKey 因为可以正常给nil
//2.也可以用setObject forKey 但如果给nil 就会Crash
//添加
[obj2 setValue:@"130" forKeyPath:@"weight"];
NSLog(@"%@",obj2);
[obj2 setObject:@"130" forKey:@"weight"];
NSLog(@"%@",obj2);
//修改
//setValue forKey 方法: 如果字典存在对应的key,那么就回修改value的值,如果不存在对应的key,就会添加对应的键值对,所以setValue forKey可以用来修改和添加
[obj2 setValue:@"100" forKey:@"weight"];
NSLog(@"%@",obj2);
//删除
//删除包含两个方法:
//1.removeObjectForKey 例如:删除@"sex"
[obj2 removeObjectForKey:@"sex"];
NSLog(@"%@",obj2);
//2.removeAllObjectss 删除所有
[obj2 removeAllObjects];
NSLog(@"没有了 %@",obj2);
//扩展题:用字典和数组表示国家,省份,城市,地区
NSDictionary *obj3 = [NSDictionary dictionaryWithObjectsAndKeys:@"China",@"Country",@"heilongjiang",@"shengfen",@"Harbin",@"City",@"acheng",@"diqu", nil];
NSDictionary *obj4 = [NSDictionary dictionaryWithObjectsAndKeys:@"America",@"Country",@"NewYork",@"NY",@"NewzeXi",@"NzX",@"abc",@"diqu", nil];
NSArray *array = [[NSArray alloc] initWithObjects:obj3,obj4, nil];
for (NSDictionary *dic in array) {
NSLog(@"%@",dic);
}
}
return 0;
}