NSDictionary的常见用法总结

        NSArray *array1 = [NSArray arrayWithObjects:@"iphone",@"ipod",nil];

        NSArray *array2 = [NSArray arrayWithObjects:@"mac",@"imac",@"mac pro",nil];

        //类方法初始化自动释放

        NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:array1,@"mobile",array2,@"computers",nil];//注意用nil结束

        NSLog(@"myDictionary = %@",myDictionary);

        

        int dictSize = [myDictionary count];

        //访问字典中的值

        NSArray *mobile = [myDictionary objectForKey:@"mobile"];

        //从一个对象获取键

        NSArray *keys = [myDictionary allKeysForObject:array1];

        //获取字典中所有值得一个数组

        NSArray *values = [myDictionary allValues];

        //快速枚举

        for(id key in myDictionary)

        {

            NSLog(@"key: %@,value: %@",key,[myDictionary objectForKey:key]);

        }

        //如果字典只包含属性列表对象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary)可以保存到文件中

        NSString *filePath = [[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:@"dict.txt"];

        BOOL success = [myDictionary writeToFile:filePath atomically:YES];

        //用文件填充

        NSDictionary *myDict2 =[NSDictionary dictionaryWithContentsOfFile:filePath];

        

        //可变字典

        NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc]initWithObjectsAndKeys:array1,@"mobile",array2,@"computer", nil];

        NSString *string4 = @"stringTV";

        //修改对象

        [dictMutable setObject:string4 forKey:@"media"];

        //删除对象

        [dictMutable removeObjectForKey:@"mobile"];

        //删除多个对象

        NSArray *keyArray =[NSArray arrayWithObjects:@"mobile",@"computer", nil];

        [dictMutable removeObjectForKey:keyArray];

        //删除所有对象

        [dictMutable removeAllObjects];

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值