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