iPhone 7
iPhone 7

Reputation: 1741

Save multiple values with same keys in NSMutableDictionary then store the dictionary in NSMutableArray

I know this question has been asked many times but not got the solution or i might not understood that's why posting the question.

for (int web=0; web<[web_arr count]; web++) {
    AdditionalBookmark *web_book=[[AdditionalBookmark alloc]init];

    UITextField *txtNam = (UITextField*)[self.view viewWithTag:1100+web];
    NSString *txtName = txtNam.text;
    UITextField *txtLin = (UITextField*)[self.view viewWithTag:1200+web];
    NSString *txtLink = txtLin.text;


       if ((txtName && txtName.length > 0)||(txtLink && txtLink.length > 0))
       {
        web_book.additionalBookmark_Name = txtName;
        web_book.additionalBookmark_Link= txtLink;
        web_book.contactDetails_Id=self.contactDetailsinfo.contactDetailsId;
        web_book.additionalBookmark_Id=[[[web_arr objectAtIndex:web] valueForKey:@"WeblinkId"] intValue];


        [dictWebLinks setObject:txtName forKey:@"WeblinkName"];
        [dictWebLinks setObject:txtLink forKey:@"WeblinkUrl"];

        [arrForWebLinks addObject:dictWebLinks];

    }
    [db updateIntoAdditionalBookmarkWithObject:web_book];
}
[dictUpdate setObject:arrForWebLinks forKey:@"Weblink"];

The problem am facing is this suppose there are two items in the array

Printing description of web_arr:
<__NSArrayM 0x170e4db60>(
{
WeblinkId = 9;
WeblinkName = Hdhd;
WeblinkUrl = "ie.comh";
},
{
WeblinkId = 10;
WeblinkName = Hd;
WeblinkUrl = "nd.com";
}
)

what i am getting is below:

Printing description of arrForWebLinks:
<__NSArrayM 0x170e4db30>(
{
WeblinkName = Hd;
WeblinkUrl = "nd.com";
},
{
WeblinkName = Hd;
WeblinkUrl = "nd.com";
}
)

dictionary is replacing the value for same key holding the latest value only, how can i mange to save the values in same format as in web_arr. Any help is appreciable.

Upvotes: 1

Views: 534

Answers (1)

Droppy
Droppy

Reputation: 9721

You are adding the same dictionary to the array over and over:

[dictWebLinks setObject:txtName forKey:@"WeblinkName"];
[dictWebLinks setObject:txtLink forKey:@"WeblinkUrl"];

[arrForWebLinks addObject:dictWebLinks];

You need to create a new one each time:

[arrForWebLinks addObject:@{
    @"WeblinkName" : txtName,
    @"WeblinkUrl"  : txtLink
}];

(and remove dictWebLinks).

Upvotes: 2

Related Questions