你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS7技巧 >> NSDictionary、NSMutableDictionary的基本用法

NSDictionary、NSMutableDictionary的基本用法

編輯:IOS7技巧
前面為各位介紹過NSDictionary自定義了但是對於那教程沒怎麼看懂的朋友可以和小編一起來看一篇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 removeObjectForKey@"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];

}

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved