首页 > 代码库 > NSDictionary--字典

NSDictionary--字典

//
//  main.m
//  OC05-task-01
//
//  Created by Xin the Great on 15-1-25.
//  Copyright (c) 2015年 Xin the Great. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NSArray+Log.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        ////////////////NSDictionary--字典///////////////////
        
        //初始化一个字典
        //注意:字典里面所装数据类型:对象,不可以是基本数据类型
        //字典是无序的
        //key 通常是字符串, key必须唯一
        NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
                             @"value",@"key",
                             @"value1",@"key1", nil];
        
        NSLog(@"dic is %@",dic);
        
        //创建一个数组
        NSArray *names = @[@"张三", @"李四", @"王五"];
        
        NSLog(@"names is %@", names);

        NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"v1",@"k1",
                              @"v2",@"k2",
                              @"v3",@"k3",
                              names,@"k4",nil];
        NSLog(@"dic2 is %@", dic2);
        
        //从字典中取出value,如果这个字典不存在这个key, 则返回null
        NSString *str = [dic2 objectForKey:@"k1"];
        NSLog(@"str is %@",str);
        NSArray *dArr = [dic2 objectForKey:@"k4"];
        NSLog(@"dArr is %@", dArr);
        NSString *str1 = [dic2 objectForKey:@"k5"];
        NSLog(@"str is %@",str1);
        
        
        //字典中键值对的个数
        NSUInteger count = [dic2 count];
        NSLog(@"count is %ld",count);
        
        //获取字典中所有的key
        NSArray *keys = [dic2 allKeys];
        NSLog(@"keys is %@",keys);
        
        //获取所有的Value
        NSArray *values = [dic2 allValues];
        NSLog(@"values is %@",values);

        //从字典中取出names的第一个元素
//        NSArray *arr = [dic2 objectForKey:@"k4"];
//        NSString *name1 = [arr objectAtIndex:0];
        //嵌套调用
        NSString *name1 = [[dic2 objectForKey:@"k4"] objectAtIndex:0];
        NSLog(@"name1 is %@", name1);
        
        
        //字典的快速创建和取值方法
        NSDictionary *dic3 = @{@"k1":@"v1",
                               @"k2":@"v2",
                               @"k3":@"v3"};
        id str2 = dic3[@"k1"];
        NSLog(@"str2 is %@",str2);
        
        
    }
    return 0;
}

NSDictionary--字典