rva
rva

Reputation: 57

How to Add objectAtIndex:i of NSArray to NSMutableDictionary

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

}

Upvotes: 1

Views: 101

Answers (3)

Teja Nandamuri
Teja Nandamuri

Reputation: 11201

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

Upvotes: 1

kanstraktar
kanstraktar

Reputation: 5357

 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.

Upvotes: 1

Sudheer Kolasani
Sudheer Kolasani

Reputation: 283

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

Upvotes: 0

Related Questions