arrays - 两个 NSArray 组合成一个具有交替值的 NSDictionary
问题描述
嗨,我对 Objective-c 很陌生,请原谅我的无知。所以基本上这就是我想要发生的事情。我有两个数字数组
Array1: (1,3,5);
Array2: (2,4,6);
我希望它们在字典中组合后变成这样
"dictionary":{"1":2,: "3":4, "5":6}
任何反馈将不胜感激!
解决方案
数组
我有两个数字数组
Array1: (1,3,5)
&Array2: (2,4,6)
我假设你有它们NSArray
并且你知道NSNumber
& Objective-C Literals。换句话说,你有:
NSArray *keys = @[@1, @3, @5]; // Array of NSNumber
NSArray *objects = @[@2, @4, @6]; // Array of NSNumber
“字典”:{“1”:2,:“3”:4,“5”:6}
我认为这意味着:
@{
@"dictionary": @{
@"1": @2,
@"3": @4,
@"5": @6
}
}
第 1 步 - 字符串化键
NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];
NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
[stringifiedKeys addObject:key.stringValue];
}
第 2 步 - 创建字典
dictionaryWithObjects:forKeys:
:
+ (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects
forKeys:(NSArray<id<NSCopying>> *)keys;
你可以这样使用它:
NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];
NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
[stringifiedKeys addObject:key.stringValue];
}
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:stringifiedKeys];
第 3 步 - 将其包装在字典中
NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];
NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
[stringifiedKeys addObject:key.stringValue];
}
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:stringifiedKeys];
NSDictionary *result = @{ @"dictionary": dictionary };
NSLog(@"%@", result);
结果:
{
dictionary = {
1 = 2;
3 = 4;
5 = 6;
};
}
手动
NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];
// Mimick dictionaryWithObjects:forKeys: behavior
if (objects.count != keys.count) {
NSString *reason = [NSString stringWithFormat:@"count of objects (%lu) differs from count of keys (%lu)", (unsigned long)objects.count, (unsigned long)keys.count];
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:reason
userInfo:nil];
}
NSMutableDictionary *inner = [NSMutableDictionary dictionaryWithCapacity:keys.count];
for (NSUInteger index = 0 ; index < keys.count ; index++) {
NSString *key = [keys[index] stringValue];
NSString *object = objects[index];
inner[key] = object;
}
NSDictionary *result = @{ @"dictionary": inner };
脚注
因为我对 Objective-C 很陌生,所以我故意避免:
- 块和更安全的枚举方式
- 轻量级泛型
- 可空性的东西
推荐阅读
- php - 如何在自定义 html 消息出错时退出 php
- android - AdapterView 不支持 Android 8.1/9.0 removeView(View)
- json - 可以将正则表达式与 JSON 和 AJAX 一起使用吗?
- javascript - Mongodb $graphLookup 构建层次结构
- node.js - NodeJS - 抛出错误作为控制流的一种方式是什么?
- javascript - Html5 canvas - 翻译功能异常
- regex - matlab又一个正则表达式问题
- angular - 从角度 6 中的函数返回 true 或 false
- python - 我提交 def 命令时给出的语法消息
- push-notification - 不知道如何在 Google 日历中开始活动时收到通知?