iOS 学习笔记4-NSDictionary 和 NSMutableDictionary

       /*
        字典:
        存储的内存不是连续的, 
        key-value 对应,
        */
// 创建方法:
        // 1.不常用,只有一组k-v
        NSDictionary* dict1 = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"];
        NSLog(@"dict1 = %@", dict1);
        // 2. 创建多个
        NSDictionary* dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"2",@"3", nil] forKeys:[NSArray arrayWithObjects:@"a", @"b", @"c", nil]];
        NSLog(@"dict2 = %@", dict2);
        
        // 3. ios5以后的简便写法
        NSDictionary* dict3 = @{@"a":@"1", @"b":@"2"};
        NSLog(@"dict3 = %@", dict3);
// 常用方法
        // count
        int count = [dict2 count];
        NSLog(@"count = %d", count);
        
        // key, value查找
        NSString* value = [dict2 valueForKey:@"b"];
        NSLog(@"value for b is %@", value);
        
        NSString* value2 =  [dict2 objectForKey:@"b"];
        NSLog(@"value2 for b is %@", value2);
        
        
        NSArray* allValues = [dict2 allValues];
        NSLog(@"all values is %@", allValues);
        
        
        NSArray* allKeys= [dict2 allKeys];
        NSLog(@"all keys are is %@", allKeys);
        
        NSArray* array = [dict2 objectsForKeys:[NSArray arrayWithObjects:@"a", @"b", @"d", nil] notFoundMarker:@"Not Found"];
        NSLog(@"array is %@", array);
        //遍历字典
        // for in 快速遍历
        for(NSString* str in dict2){
            NSLog(@"the key is %@, the value is %@", str, dict2[str]);
        }
        //2. 枚举器遍历
        NSEnumerator* en = [dict2 keyEnumerator];
        id key = nil;
        while(key = [en nextObject]){
            NSLog(@"key - %@", key);
            
        }
 //NSMutableDictionary
        // 1. 添加
        NSMutableDictionary* dict4 = [[NSMutableDictionary alloc] init]; // 不需要初始赋值,因为可以随时添加
        [dict4 setObject:@"1" forKey:@"a"];
        [dict4 setObject:@"2" forKey:@"b"];
        [dict4 setObject:@"3" forKey:@"c"];
        [dict4 setObject:@"4" forKey:@"d"];
        // 2. 删除
        [dict4 removeObjectForKey:@"a"];
        
        [dict4 removeObjectsForKeys: [NSArray arrayWithObjects:@"a",@"b", nil]];
        
        [dict4 removeAllObjects];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值