第三彈 NSDictionary字典類型 發(fā)射
NSDictionary字典類型可以將數(shù)據(jù)以鍵值對的形式儲存起來盗忱,取值的時候通過key就可以直接拿到對應(yīng)的值茂嗓,非常方便,在同一個詞典對象中可以保存多個不同類型的數(shù)據(jù).
創(chuàng)建NSDictionary 與 取元素
// key 與 value 一一對應(yīng)
NSDictionary *dict1 = [NSDictionary dictionary];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"zs" forKey:@"name"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObjects:@[@"zs",@"22",@"183"] forKeys:@[@"name",@"age",@"height"]];
NSDictionary *dict4 = @{@"zs" : @"name", @"22" : @"age", @"183" : @"height"};
NSLog(@"name=%@ age=%@ height=%@", dict3[@"name"], dict3[@"age"], dict3[@"height"]);
NSLog(@"name=%@ age=%@ height=%@", [dict3 objectForKey:@"name"], [dict3 objectForKey:@"age"], [dict3 objectForKey:@"height"]);
遍歷字典元素
NSUInteger count = [dict3 count]; //取字典數(shù)量
//for循環(huán)取元素
for (int i = 0; i < count; ++i) {
// 獲取字典中所有的key
NSArray *keys = [dict3 allKeys];
// 取出當(dāng)前位置對應(yīng)的key
NSString *key = keys[i];
NSString *value = dict3[key];
NSLog(@"key = %@, value = %@", key, value);
}
// 如何通過forin遍歷字典
for (NSString *key in dict3) {
NSString *value = dict3[key];
NSLog(@"key = %@, value = %@", key, value);
}
/**
* 使用OC字典的迭代器來遍歷 官方推薦使用
*
* @param key 鍵
* @param obj value 值
* @param stop 控制停止
*/
[dict3 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"key = %@, value = %@", key, obj);
}];
字典和文件
//將字典寫入文件
[dict3 writeToFile:@"/Users/xxx/Desktop/dict.plist" atomically:YES];
//從文件中讀取字典
NSDictionary *dictFile = [NSDictionary dictionaryWithContentsOfFile:@"/Users/xxx/Desktop/dict.plist"];
可變字典 NSMutableDictionary
//創(chuàng)建可變字典
NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
[mDict setObject:@"zs" forKey:@"name"]; //同名的key賦值, 那么新值會覆蓋舊值
[mDict setValuesForKeysWithDictionary:@{@"age":@"22",@"height":@"183"}];
NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithObjects:@[@"zs", @"ls"] forKeys:@[@"name", @"name"]];
NSLog(@"mdit = %@",mdict); //ls
//取數(shù)據(jù)
[mDict valueForKey:@"name"];
NSLog(@"age = %@", mDict[@"age"]);
//刪除數(shù)據(jù)
[mDict removeObjectForKey:@"name"];
[mDict removeAllObjects];
//不可變字典出現(xiàn)了同名的key, 那么后面的key對應(yīng)的值不會被保存
NSDictionary *dictM = @{@"name":@"zs", @"name":@"ls"};
NSLog(@"dictM = %@", dictM); // name = zs
MarkDown文本和代碼均可在github上下載:GitHub地址 : CoderVan