字典是OC中一種特殊的類型,功能非常強大。是Foundation中的重要組成部分。我們來學習一下:
#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... /* 字典: 1.儲存的記憶體不是連續的; 2.用key和value進行對應(索引值); 3.KVC:索引值編碼; */ //建立方式1; NSDictionary *dict = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"]; NSLog(@"%@",dict); //建立方式2: NSArray *arrValue = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil]; NSArray *arrKeys = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d", nil]; NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:arrValue forKeys:arrKeys]; NSLog(@"%@",dict1); //建立方式3:簡便建立方式; //@{} ;表示字典;!!!!! NSDictionary *dict3 = @{@"1":@"a",@"2":@"b"}; NSLog(@"%@",dict3); //長度: int count = (int)dict3.count; NSLog(@"count = %d",count); //根據鍵擷取值 NSString *str = [dict3 objectForKey:@"2"]; NSLog(@"索引值 = %@",str); //也可以使用下面的方法: NSString *str2 = [dict3 valueForKey:@"2"]; NSLog(@"索引值 = %@",str2); //擷取字典中的所有值;(value) NSArray *arr5 = [[NSArray alloc] initWithObjects:@"1",@"2", @"3",nil]; NSArray *arrAllValue = [dict3 objectsForKeys:arr5 notFoundMarker:@"none"]; NSLog(@"所有值方法1 = %@",arrAllValue); //還有一種擷取所有值的方法; NSArray *arrAllValue2 = [dict3 allValues]; NSLog(@"所有值方法2 = %@",arrAllValue2); //擷取字典中的所有鍵;(key) NSArray *arrAllKey = [dict3 allKeys]; NSLog(@"所有鍵 = %@",arrAllKey); //遍曆數組; //需要使用鍵去遍曆; for (NSString *key in dict3) { NSString *value = [dict3 objectForKey:key]; NSLog(@"key = %@,value = %@",key,value); } //使用迭代器進行遍曆; NSEnumerator *en = [dict3 keyEnumerator]; id key = nil; while (key = [en nextObject]) { NSString *str = [dict3 objectForKey:key]; NSLog(@"迭代器擷取值 = %@",str); } } return 0;}
輸出結果如下:
.
github首頁:https://github.com/chenyufeng1991 。歡迎大家訪問。