1

How to Add objectAtIndex:i of NSArray to NSMutableDictionary

i have tried

for(int i=0 ;i<=[user count]; i++){

NSMutableDictionary * dict = [NSMutableDictionary :[user objectAtIndex:i]];

}
rva
  • 57
  • 1
  • 9
  • you can set a value with key like NSMutableDictionary *Dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[Arr objectAtIndex:i],@"somekey", nil] – Chirag D jinjuwadiya Oct 25 '16 at 13:15

3 Answers3

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]];
 }

Careful with this one: i<[user count], as the way you're doing it now you're going to get a message of array index out bounds. Of course, you could set the key for each element however you may want.

kanstraktar
  • 5,357
  • 2
  • 21
  • 29
1

Instead of for loop, use the enumerate block:

    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]];
    }];
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109
0

try this....

NSArray * myArray = [NSArray arrayWithObjects:@"a", @"b", @"c"];

NSDictionary * dict = [NSDictionary dictionaryWithObject:myArray forKey:@"threeLetters"];

NSMutableDictionary * mutableDict = [NSMutableDictionary dictionaryWithCapacity:10];
[mutableDict setObject:myArray forKey:@"threeLetters"];
Sudheer Kolasani
  • 283
  • 5
  • 28