黑馬程式員_學習IOS之字典常用的方法

來源:互聯網
上載者:User

標籤:style   ext   color   strong   使用   資料   

字典是無序的 數組是有序的。字典分為:可變字典和不可變字典


 不可變字典對象


NSDictionary * dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3",@"four",@"4", nil];
//value = key
//初始化必須一一對應 字典的內容是索引值對 key->value 內容可以是任意的對象指標
//key 一般是NSString * value 可以是任意對象
//不能出現重複的key key是唯一的

NSDictionary * dict1 = [NSDictionary dictionaryWithDictionary:dict];

NSArray * values = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
NSArray * keys = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];//key-value要一一對應
NSDictionary * dict2 = [[NSDictionary alloc]initWithObjects:values forKeys:keys];

[dict count]//索引值對的個數 索引值對必須成對出現
[dict objectForKey:@"5"]//根據key找到對應的value

//建立一個key的列舉程式 把字典中key元素地址傳給列舉程式
NSEnumerator * enumer1 = [dict keyEnumerator];
id obj;
while (obj = [enumer1 nextObject]) {
NSLog(@"%@",[dict objectForKey:obj]);
}

//建立值的列舉程式(一般不使用,沒有意義)
NSEnumerator * enumer2 = [dict objectEnumerator];
while (obj = [enumer2 nextObject]) {
NSLog(@"%@",obj);
}
//快速枚舉 枚舉的是key(不能改資料,只能讀)
for(id key in dict){
NSLog(@"%@",key);
}

NSArray * array = [urlItemDict allValues];//擷取所有value
NSArray * array = [urlItemDict allKeys];//擷取所有key------可變字典對象

可變字典對象

NSMutableDictionary * dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3",@"four",@"4", nil];

[dict setObject:@"seven" forKey:@"7"];//增加索引值對 key已經存在 則修改value 不存在則添加
[dict setObject:@"nine" forKey:@"1"];//修改value
[dict removeObjectForKey:@"1"];//刪除索引值對

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.