how to add namearr array to my dictionary

56 Views Asked by At
NSArray* nameArr = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", @"Jack Lolwut",
                    @"Mike Roflcoptor", @"Cindy Woods", @"Jessica Windmill", @"Alexander The Great",
                    @"Sarah Peterson", @"Scott Scottland", @"Geoff Fanta", @"Amanda Pope", @"Michael Meyers",
                    @"Richard Biggus", @"Montey Python", @"Mike Wut", @"Fake Person", @"Chair",@"subbu",@"reddy",@"suresh",@"harish",@"naresh",@"giri",@"nani",
                    nil];

for (i=0; i<=nameArr.count i++)
{
    NSMutableDictionary *dic=[NSMutableDictionary new];
    [dic setObject:@"nameArr" forKey:@"name"];
}
4

There are 4 best solutions below

2
vivek bhoraniya On

You are creating NSMutableDictionary object each and every time.

You should declare that object out side of for loop.

Here is the code

NSMutableDictionary *dic=[NSMutableDictionary new];
for (i=0; i<=nameArr.count i++)
{
  NSString *nameObj = nameArr[i];
  [dic setObject:nameObj forKey:@"name"];
}

But clear the purpose as this code is not proper.

It states that you are compiling loop number of item array has, and you are adding same array to that dictionary on same key.

0
NeverHopeless On

Try like this:

NSMutableDictionary *dic = @{ @"name" : nameArr}.mutableCopy;
3
KKRocks On

Try this :

If you want to add array .

NSMutableDictionary *dic = @{ @"name" : nameArr}. mutableCopy;

If you want to add array objects.

   NSMutableDictionary *dic=[NSMutableDictionary new];

   for (NSString *strname in nameArr) {
        [dic setObject:strname forKey:@"name"]
    }
0
iYoung On

Currently you are adding nameArr as a string, in case you need to add array for a particular key try below:

NSMutableDictionary *nameDictionary = [NSMutableDictionary new];
[dic setObject:nameArr forKey:@"name"];

Hope this helps!