NSDictionary的常見用法總結

2021-06-10 07:03:38 字數 1473 閱讀 7272

nsarray *array1 = [nsarray arraywithobjects:@"iphone",@"ipod",nil];

nsarray *array2 = [nsarray arraywithobjects:@"mac",@"imac",@"mac pro",nil];

//類方法初始化自動釋放

nsdictionary *mydictionary = [nsdictionary dictionarywithobjectsandkeys:array1,@"mobile",array2,@"computers",nil];//注意用nil結束

nslog(@"mydictionary = %@",mydictionary);

int dictsize = [mydictionary count];

//訪問字典中的值

nsarray *mobile = [mydictionary objectforkey:@"mobile"];

//從乙個物件獲取鍵

nsarray *keys = [mydictionary allkeysforobject:array1];

//獲取字典中所有值得乙個陣列

nsarray *values = [mydictionary allvalues];

//快速列舉

for(id key in mydictionary)

//如果字典只包含屬性列表物件(nsdata,nsdate,nsnumber,nsstring,nsarray或nsdictionary)可以儲存到檔案中

bool success = [mydictionary writetofile:filepath atomically:yes];

//用檔案填充

nsdictionary *mydict2 =[nsdictionary dictionarywithcontentsoffile:filepath];

//可變字典

nsmutabledictionary *dictmutable = [[nsmutabledictionary alloc]initwithobjectsandkeys:array1,@"mobile",array2,@"computer", nil];

nsstring *string4 = @"stringtv";

//修改物件

[dictmutable setobject:string4 forkey:@"media"];

//刪除物件

[dictmutable removeobjectforkey:@"mobile"];

//刪除多個物件

nsarray *keyarray =[nsarray arraywithobjects:@"mobile",@"computer", nil];

[dictmutable removeobjectforkey:keyarray];

//刪除所有物件

[dictmutable removeallobjects];

API之NSDictionary的常見用法

nsdictionary dic1 nsdictionary alloc initwithobjectsandkeys 李四 name 不明 gender nil 字典中的物件可以重複儲存 71 instancetype initwithobjectsandkeys id firstobject,n...

簡單常用 NSDictionary

新增我們的測試 nsdictionary dictionary nsdictionary dictionarywithobjectsandkeys lucy name 15810463139 number nil 得到詞典的數量 nsinteger mcount dictionary count n...

NSDictionary實現原理

nsdictionary 字典 是使用 hash表來實現key和value之間的對映和儲存的,hash函式設計的好壞影響著資料的查詢訪問效率。資料在hash表中分布的越均勻,其訪問效率越高。而在objective c中,通常都是利用nsstring 來作為鍵值,其內部使用的hash函式也是通過使用 ...