NSDictionary 使用总结

        NSArray *m_array = [NSArray arrayWithObjects:@"first",@"second",nil];
        NSArray *n_array = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];
        //使用类方法初始化,系统自动释放内存
        NSDictionary *test_dictionary = [NSDictionary dictionaryWithObjectsAndKeys:m_array,@"sort",n_array,@"number",nil];
        NSLog(@"myDictionary = %@",myDictionary);
        //获取字典包含对象数目
        int dict_size = [test_dictionary count];
        //访问字典中的值
        NSArray *sort_array = [test_dictionary objectForKey:@"sort"];
        //获取键值
        NSArray *keys = [test_dictionary allKeysForObject:sort_array];
        //获取字典中所有值,数组
        NSArray *all_value = [test_dictionary allValues];
        //快速枚举
        for(id key in test_dictionary)
        {
            NSLog(@"key: %@,value: %@",key,[test_dictionary objectForKey:key]);
        }
        //如果字典只包含属性列表对象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary)可以保存到文件中
        NSString *filePath = [[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:@"test_dict.plist"];
        [test_dictionary writeToFile:filePath atomically:YES];
        //用文件填充
        NSDictionary *myDict =[NSDictionary dictionaryWithContentsOfFile:filePath];
        
        //可变字典
        NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc]initWithObjectsAndKeys:m_array,@"sort",n_array,@"number", nil];
        NSString *str = @"10_10";
        //修改对象
        [dictMutable setObject:string4 forKey:@"sort"];
        //删除对象
        [dictMutable removeObjectForKey:@"number"];
        //删除多个对象
        NSArray *key_array =[NSArray arrayWithObjects:@"sort",@"number", nil];
        [dictMutable removeObjectForKey:key_array];
        //删除所有对象
        [dictMutable removeAllObjects];

posted @ 2013-01-10 10:05  沙影无痕  阅读(121)  评论(0编辑  收藏  举报