OC中的字典以及常用方法

2021-06-26 09:14:46 字數 2130 閱讀 8362

//建立乙個字典

//初始化

nsdictionary

*dict1 = [[

nsdictionary

alloc

]initwithobjectsandkeys

:@"張三",@"name",@"男",@"***",@"18",@"age",

nil];

nslog(@"%@",dict1);

//建立乙個鍵陣列

nsarray *keyarray = [nsarray

arraywithobjects:@"name",@"***",@"age",nil];

//建立乙個值陣列

nsarray *valuearray = [nsarray

arraywithobjects:@"

張三",@"

男",@"18",nil];

//第二個建立字典的方法

nsdictionary *dict2 = [[nsdictionary

alloc]initwithobjects:valuearrayforkeys:keyarray];

nslog(@"%@",dict2);

//第三個建立字典的方法

nsdictionary *dict3 = [nsdictionary

dictionarywithdictionary:dict2];

nslog(@"%@",dict3);

//取出字典裡的key值

nsarray *arr1 = [dict3allkeys];

nslog(@"%@",arr1);

//取出字典裡的value值

nsarray *arr2 = [dict3allvalues];

nslog(@"%@",arr2);

//取出字典裡的key對應的value值

nsstring *s1 = [dict3objectforkey:@"name"];

nslog(@"%@",s1);

//可變字典

nsmutabledictionary*mdict1 = [nsmutabledictionary

dictionary];

//新增元素

[mdict1setobject:@"18"

forkey:@"age"];

nslog(@"%@",mdict1);

//刪除元素

[mdict1 removeobjectforkey:

@"age"];

nslog(@"%@",mdict1);

//修改元素:有則改之無則加勉

[mdict1setobject:@"w"

forkey:@"123"];

nslog(@"%@",mdict1);

//給mdict1增加元素

[mdict1setobject:@"18"

forkey:@"age"];

[mdict1setobject:@"lily"

forkey:@"name"];

[mdict1setobject:@"f"

forkey:@"***"];

//字典套字典

nsmutabledictionary*mdict2 = [nsmutabledictionary

dictionarywithdictionary

:mdict1];

nslog(@"%@",mdict2);

//陣列裡元素是字典

nsarray *arr3 = [nsarray

arraywithobjects:mdict1,mdict2 ,nil];

nslog(@"%@",arr3);

//字典裡元素是陣列

nsdictionary

*dict4 = [

nsdictionary

dictionarywithobject:arr2forkey:

@"name"];

nslog(@"%@",dict4);

//取出陣列裡的元素(字典)

nsarray *arr4 = [dict4valueforkey:@"name"];

//取出(陣列裡的)字典的值

nsdictionary *dict5 = arr4[0];

OC中NSString 的常用方法

nsstring str1 beijing nsstring str2 beijing 全部轉為大寫 nslog str1 uppercasestring 全部轉為小寫 nslog str1 lowercasestring 首字母大寫 nslog str1 capitalizedstring 比較兩...

OC 中 NSArray 的常用方法

1 陣列的基本概念 foundation中的陣列 nsarray,nsmutablearray 是一組有序的物件集合,通過索引下標獲取到陣列中的 各個元素.與字串相同,陣列也是可變和不可變陣列之分.此外,陣列中不可以存放基本陣列型別,只能存放類的 例項 物件 如若需要將基本資料型別,結構體放入陣列中...

OC中NSString 的常用方法

cpp view plain copy nsstring str1 beijing nsstring str2 beijing 全部轉為大寫 nslog str1 uppercasestring 全部轉為小寫 nslog str1 lowercasestring 首字母大寫 nslog str1 c...