Objective-C中NSNumber与NSDictionary的用法简介

2020-01-14 16:45:33于丽

    
   //字典中所有的key
    NSArray * keys = [NSArray arrayWithObjects:@"name",@"sex",@"age",nil];
   //字典中所有跟key对应的value
    NSArray * values = [NSArray arrayWithObjects:@"liuhui",@"男",[NSNumbernumberWithInt:36],nil];
   //创建字典对象方法1
    NSDictionary * myDic = [[NSDictionary alloc]initWithObjects:values forKeys:keys];
    NSLog(@"my dic = %@",myDic);
   // 创建字典对象方法2    
    NSDictionary * yourDic = [[NSDictionary alloc] initWithObjectsAndKeys:skyAArrays,@"A",skyBArrays,@"B",skyCArrays,@"C",nil];
    NSLog(@"your dic = %@",yourDic);
    
    NSLog(@"%@",[yourDic objectForKey:@"A"]);
    // - (NSArray *)allKeys; 返回的是 NSArray类型,方便用 objectAtIndex取出一个个key
    NSLog(@"%@",[yourDic allKeys]);
    NSLog(@"%@",[yourDic allValues]);
    
   //添加数据(setObject 一般没有一种key才添加,有同名的key而用这种方法,会覆盖掉),注意:id key  是成对出现的  
    [mutableDictionary setObject:@"good lucky"forKey:@"why"];  
    [mutableDictionary setObject:@"bye bye" forKey:@"how"]; 

 


   //删除指定键值的数据  
    [mutableDictionary removeObjectForKey:..];  
   //删除所有数据  
    [mutableDictionary removeAllObjects]; 

    //字典的普通遍历(无序)
    for (int i =0; i < [yourDic count]; i++) {     
        NSLog(@"key = value <====> %@ = %@",[[yourDic allKeys] objectAtIndex:i],[yourDic objectForKey:[[yourDic allKeys]objectAtIndex:i]]);
    }
    
    // 字典的快速遍历 取出来的obj一定是key
    for (id obj in yourDic) {    
        NSLog(@"%@",obj);
        id value = [yourDic objectForKey:obj];   
        NSLog(@"%@",value);
    }