Objective - C NSDictionary不可變字典和NSMutableDictionary可變字典

來源:互聯網
上載者:User

標籤:

 

//建立一個不可變的字典對象

    //便利構造器建立

    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhonger", @"name2", @"taixu", @"name1", @"caicai", @"name3", nil];

 

    //初始化方法

    //先給value 再給key

    NSDictionary *dic1 = [[NSDictionary alloc]initWithObjectsAndKeys:@"zhonger", @"name2", @"taixu", @"name1", @"caicai", @"name3", nil];

    

    NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:@[@"name1", @"name2", @"name3"] forKeys:@[@"zhonger", @"name2", @"taixu"]];

    

    //笑笑文法

    //key 在前 value在後

    NSDictionary *dic3 = @{@"name1":@"zhanger", @"name2":@"caicai", @"name3":@"fufu"};

    

    //擷取字典中索引值對的個數,以及擷取所有的key和所有的value;

    NSUInteger count = [dic3 count];

    

    NSArray *arr = [dic3 allKeys];

    

    NSLog(@"dic3 allkeys is %@",arr);

    

    NSLog(@"dic3 allvalue is %@",[dic3 allValues]);

    

    //擷取字典中的某個value值,通過key

    NSString *string = [dic3 objectForKey:@"name2"];

   

    NSArray *allkeys = [dic3 allKeys];

    for (int i = 0; i < [allkeys count]; i ++) {

        NSLog(@" %@",[dic3 objectForKey:allkeys[i]]);

    }

    

    

    //建立可變字典對象,初始化方法,便利構造器,字面量

    NSMutableDictionary *mDic = [[NSMutableDictionary alloc] initWithCapacity:0];

    NSMutableDictionary *mDic1 = [NSMutableDictionary dictionaryWithCapacity:0];

    NSMutableDictionary *mDic2 = [@{@"key1":@"zhangsan", @"key2":@"lisi", @"key3":@"wangwu"}mutableCopy];

    NSLog(@"mDic2 is %@",mDic2);

    

    //增加索引值對的方法 setObject:forkey:

    [mDic2 setObject:@"liumazi" forKey:@"key4"];

    NSLog(@"mDic2 is %@",mDic2);

    

    //刪除索引值對的方法,刪除之後,key和value都不存在了

    //removeObjectForKey:

    [mDic2 removeObjectForKey:@"key2"];

    NSLog(@"mDic2 is %@",mDic2);

    

    //移除所有的索引值對

    [mDic2 removeAllObjects];

    NSLog(@"mDic2 is %@",mDic2);

    

    //修改索引值對的方法和增加索引值對的方法是一樣的。。

    [mDic2 setObject:@"zhangsan" forKey:@"key1"];

    NSLog(@"mDic2 is %@",mDic2);

    [mDic2 setObject:@"lisi" forKey:@"key1"];

    NSLog(@"mDic2 is %@",mDic2);

    //字典中的Key是不能重複的 但是value可以重複,並且字典是一個無序集合

Objective - C NSDictionary不可變字典和NSMutableDictionary可變字典

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.