程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> NSDictionary

NSDictionary

編輯:關於C++
//
//  main.m
//  OC05-task-01
//
//  Created by Xin the Great on 15-1-25.
//  Copyright (c) 2015年 Xin the Great. All rights reserved.
//

#import 
#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;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved