Arrays
I have two arrays of numbers Array1: (1,3,5)
& Array2: (2,4,6)
I assume that you have them in NSArray
and that you're aware of NSNumber
& Objective-C Literals. In other words, you have:
NSArray *keys = @[@1, @3, @5]; // Array of NSNumber
NSArray *objects = @[@2, @4, @6]; // Array of NSNumber
"dictionary":{"1":2,: "3":4, "5":6}
I assume that it means:
@{
@"dictionary": @{
@"1": @2,
@"3": @4,
@"5": @6
}
}
Step 1 - Stringify 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];
}
Step 2 - Create a dictionary
dictionaryWithObjects:forKeys:
:
+ (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects
forKeys:(NSArray<id<NSCopying>> *)keys;
You can use it in this way:
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];
Step 3 - Wrap it in a dictionary
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);
Result:
{
dictionary = {
1 = 2;
3 = 4;
5 = 6;
};
}
Manually
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 };
Footnotes
Because of I am very new to Objective-C, I did intentionally avoid:
- Blocks & safer ways to enumerate
- Lightweight generics
- Nullability stuff