IOS筆記之字典

翻身不做鹹魚發表於2018-07-15

字典儲存的內容不是連續的,用key和value進行對應。

1.字典初始化
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSLog(@"dict1 = %@",dict1);

NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value1",@"value2", nil ]forKeys:[NSArray arrayWithObjects:@"key1",@"key2", nil] ];
NSLog(@"dict2=%@",dict2);


NSDictionary *dict3 = @{@"key":@"value",@"key1":@"value1"};
NSLog(@"dict3=%@",dict3);
複製程式碼
2.長度
int count = (int)[dict1 count];
複製程式碼
3.取值
//取值
NSString *value = [dict1 objectForKey:@"key"];
NSLog(@"value= %@",value);
NSString *value1 =[dict3 valueForKey:@"key1"];
NSLog(@"value1 =%@",value1);
//取出所有值
NSArray *array = [dict3 allValues];
NSLog(@"allvalues =%@",array);

//取出所有key
[dict3 allKeys];

NSArray *values = [dict3 objectsForKeys:[NSArray arrayWithObjects:@"key",@"1", nil] notFoundMarker:@"not found"];
NSLog(@"values = %@",values);
複製程式碼
4.遍歷
//for迴圈遍歷
for (NSString *key in dict3) {
 NSLog(@"%@=%@",key,[dict3 objectForKey:key]);
}

//迭代遍歷
NSEnumerator *en = [dict3 keyEnumerator];
 id key1 = nil;
 while (key1 = [en nextObject]) {
 NSLog(@"key-%@",key1);
}
複製程式碼

相關文章