[BS-14] 打印NSArray和NSDictionary的3种方法

时间:2022-10-06 11:04:45

打印NSArray和NSDictionary的3种方法

    NSArray *arr = @[@"奔驰",@"宝马",@"路虎",@"Tesla"];
//1.直接打印
NSLog(@"arr:%@",arr);
//2.使用for...in遍历
for (NSString *str in arr) {
NSLog(@"%@",str);
}
//3.使用枚举遍历
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"arr[%lu] = %@",(unsigned long)idx,obj);
}]; /*打印结果如下: 2016-05-06 23:06:21.876 打印NSArray和NSDictionary[4048:370831] arr:(
"\U5954\U9a70",
"\U5b9d\U9a6c",
"\U8def\U864e",
Tesla
) 2016-05-06 23:06:21.877 打印NSArray和NSDictionary[4048:370831] 奔驰
2016-05-06 23:06:21.877 打印NSArray和NSDictionary[4048:370831] 宝马
2016-05-06 23:06:21.877 打印NSArray和NSDictionary[4048:370831] 路虎
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] Tesla 2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] arr[0] = 奔驰
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] arr[1] = 宝马
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] arr[2] = 路虎
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] arr[3] = Tesla
*/ NSDictionary *dict = @{@"name":@"Steven",
@"sex":@"M",
@"age":@,
};
//1.直接打印
NSLog(@"dict:%@",dict);
//2.使用for...in遍历
for (NSString *key in dict.allKeys) {
NSLog(@"%@:%@",key,dict[key]);
}
//3.使用枚举遍历
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"%@-%@",key,obj);
}];
} /*打印结果如下: 2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] dict:{
age = 26;
name = Steven;
sex = M;
}
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] sex:M
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] name:Steven
2016-05-06 23:06:21.878 打印NSArray和NSDictionary[4048:370831] age:26
2016-05-06 23:06:21.879 打印NSArray和NSDictionary[4048:370831] sex-M
2016-05-06 23:06:21.965 打印NSArray和NSDictionary[4048:370831] name-Steven
2016-05-06 23:06:21.965 打印NSArray和NSDictionary[4048:370831] age-26
*/