如何将objectAtIndex:i
NSArray
添加到NSMutableDictionary
我试过了
for(int i=0 ;i<=[user count]; i++){
NSMutableDictionary * dict = [NSMutableDictionary :[user objectAtIndex:i]];
}
答案 0 :(得分:1)
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:[user count]];
for(int i=0 ;i<[user count]; i++) {
[dic setObject:[user objectAtIndex:i] forKey:[NSString stringWithFormat:@"%i", i]];
}
小心这个:i&lt; [用户数],就像你现在这样做的方式,你将得到一个数组索引输出边界的消息。当然,您可以根据需要设置每个元素的键。
答案 1 :(得分:1)
使用枚举块:
而不是for循环 NSArray *arr;
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[dic setObject:obj forKey:[NSString stringWithFormat:@"%lu", (unsigned long)idx]];
}];
答案 2 :(得分:0)
试试这个......
NSArray * myArray = [NSArray arrayWithObjects:@"a", @"b", @"c"];
NSDictionary * dict = [NSDictionary dictionaryWithObject:myArray forKey:@"threeLetters"];
NSMutableDictionary * mutableDict = [NSMutableDictionary dictionaryWithCapacity:10];
[mutableDict setObject:myArray forKey:@"threeLetters"];