两个 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文字。换句话说,您有:

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很陌生,所以我确实有意避免:

  • 阻止和更安全的枚举方法
  • 轻量级泛型
  • 可空性的东西

您可以使用以下代码尝试:

- (NSDictionary *)convertToDicFromKeys:(NSArray *)keys andValues:(NSArray *)values
{
NSInteger count = MIN(keys.count, values.count);
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:count];
for (int i = 0; i < count; i++) {
dic[keys[i]] = values[i];
}
return dic;
}

最新更新