首页 > 解决方案 > 两个 NSArray 组合成一个具有交替值的 NSDictionary

问题描述

嗨,我对 Objective-c 很陌生,请原谅我的无知。所以基本上这就是我想要发生的事情。我有两个数字数组

Array1: (1,3,5);
Array2: (2,4,6);

我希望它们在字典中组合后变成这样

"dictionary":{"1":2,: "3":4, "5":6}

任何反馈将不胜感激!

标签: arraysobjective-cdictionarydata-structuresconcatenation

解决方案


数组

我有两个数字数组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 很陌生,所以我故意避免:

  • 块和更安全的枚举方式
  • 轻量级泛型
  • 可空性的东西

推荐阅读