IOS Intro - NSDictionary and NSMutableDictionary

來源:互聯網
上載者:User

標籤:eve   nil   sar   包含   table   刪除   str   san   log   

 

 

 

NSDictionary、NSMutableDictionary的基本用法

1.不可變詞典NSDictionary

字典初始化

NSNumber *numObj = [NSNumber numberWithInt:100];

以一個元素初始化

NSDictionary *dic = [NSDictionary dictionaryWithObject:numObj forKey:@"key"];

初始化兩個元素

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:numObj, @"valueKey", numObj2, @"value2",nil];

初始化新字典,新字典包含otherDic

NSDictionary *dic = [NSDictionary dictionaryWithDictionary:otherDic];

以檔案內容初始化字典

NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];

 

常用方法

擷取字典數量

NSInteger count = [dic count];

通過key擷取對應的value對象

NSObject *valueObj = [dic objectForKey:@"key"];

將字典的key轉成枚舉對象,用於遍曆

NSEnumerator *enumerator = [dic keyEnumerator];

擷取所有鍵的集合

NSArray *keys = [dic allKeys];

擷取所有值的集合

NSArray *values = [dic allValues];

 

2.可變數組NSMutableDictionary

初始化一個空的可變字典

NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"key1",@"v2",@"key2",nil];

NSDictionary *dic3 = [NSDictionary dictionaryWithObject:@"v3" forKey:@"key3"];

向字典2對象中添加整個字典對象3

[dic2 addEntriesFromDictionary:dic3];

向字典2對象中最佳一個新的key3和value3

[dic2 setValue:@"value3" forKey:@"key3"];

初始化一個空的可變字典

NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];

將空字典1對象內容設定與字典2對象相同

[dic1 setDictionary:dic2];

將字典中key1對應的值刪除

[dic1 [email protected]"key1"];

NSArray *array = [NSArray arrayWithObjects:@"key1", nil];

根據指定的數組(key)移除字典1的內容

[dic2 removeObjectsForKeys:array];

移除字典所有對象

[dic1 removeAllObjects];

 

遍曆字典

快速枚舉

for (id key in dic){

     id obj = [dic objectForKey:key];

     NSLog(@"%@", obj);

}

一般枚舉

NSArray *keys = [dic allKeys];

inr length = [keys count];

for (int i = 0; i < length;i++){

     id key = [keys objectAtIndex:i];

     id obj = [dic objectForKey:key];

     NSLog(@"%@", obj);

}

通過枚舉類型枚舉

NSEnumerator *enumerator = [dic keyEnumerator];

id key = [enumerator nextObject];

while (key) {

        id obj = [dic objectForKey:key];

        NSLog(@"%@", obj);

        key = [enumerator nextObject];

}

IOS Intro - NSDictionary and 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.