When I try add NSDictionary into NSMutableArray I can't replace the last object addedHow do I sort an NSMutableArray with custom objects in it?NSDictionary into 1 NSMutableArrayHelp me sort NSMutableArray full of NSDictionary objects - Objective CManipulating with NSMutableArray And NSMutableDictionary Objective CNSMutableDictionary SetObject:ForKey: is not inserting NSDictionary objectObjective C - Leak when setting an array as an object of a dictionarySpilt an NSMutableArray of NSDictionariesCheck if an object exist in a NSMutableArray of NSDictionaryAdd to NSMutableDictionary without replacing similar keysNSMutableArray of custom objects -> NSMutableArray of NSMutableArrays of similar dictionaries and NSDictionaries

Was Richard I's imprisonment by Leopold of Austria justified?

Secure my password from unsafe servers

Traveling from Germany to other countries by train?

Colleagues speaking another language and it impacts work

What are these mathematical groups in U.S. universities?

Did WWII Japanese soldiers engage in cannibalism of their enemies?

Probably terminated or laid off soon; confront or not?

Does a 4 bladed prop have almost twice the thrust of a 2 bladed prop?

I was contacted by a private bank overseas to get my inheritance

How to help new students accept function notation

Why can I log in to my Facebook account with a misspelled email/password?

12V lead acid charger with LM317 not charging

Why ReLU function is not differentiable at 0?

Will a paper be retracted if a flaw in released software code invalidates its central idea?

How to realistically deal with a shield user?

Capacitors with a "/" on schematic

Count number of occurences of particular numbers in list

Based on what criteria do you add/not add icons to labels within a toolbar?

What is an air conditioner compressor hard start kit and how does it work?

Is there a drawback to Flail Snail's Shell defense?

Cobb-Douglas production function with expenditures rather than units

How can glass marbles naturally occur in a desert?

Getting an entry level IT position later in life

What could prevent players from leaving an island?



When I try add NSDictionary into NSMutableArray I can't replace the last object added


How do I sort an NSMutableArray with custom objects in it?NSDictionary into 1 NSMutableArrayHelp me sort NSMutableArray full of NSDictionary objects - Objective CManipulating with NSMutableArray And NSMutableDictionary Objective CNSMutableDictionary SetObject:ForKey: is not inserting NSDictionary objectObjective C - Leak when setting an array as an object of a dictionarySpilt an NSMutableArray of NSDictionariesCheck if an object exist in a NSMutableArray of NSDictionaryAdd to NSMutableDictionary without replacing similar keysNSMutableArray of custom objects -> NSMutableArray of NSMutableArrays of similar dictionaries and NSDictionaries






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I need to add NSDictionary into NSMutableArray.



First I have created a NSMutableDictionary with a key value from other structure like this:



for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



selectedFiltersByUser is a Dictionary like this:




category_id = "XXX";
sort = "last_updated_asc";
status = "rejected_by_seller";



and for each key:value in this Dictionary I create a new NSMutableDictionary like this:




key: category_id,
value: XXX



And this new NSMutableDictionary added into NSMutableArray like this:



 for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



But when adding this NSMutableDictionary into NSMutableArray it doesn't replace the last object and I get this in query_params:



 
key: category_id,
value: XXX
,

key: category_id,
value: XXX
,

key: category_id,
value: XXX



I need this:




key: category_id,
value: XXX
,

key: sort,
value: last_updated_asc
,

key: status,
value: rejected_by_seller



I don't know how to replace the last object added.










share|improve this question





















  • 1





    try to [NSDictionary alloc] init] in the for loop and then add data.

    – Nirav Kotecha
    Mar 27 at 4:59











  • Into the loop? But I init out of the loop. I created a new NSMutableDictionary for each element and then added into other structure? @NiravKotecha

    – Josué H.
    Mar 27 at 5:02











  • yes into the loop.

    – Nirav Kotecha
    Mar 27 at 5:05












  • when you init out of the loop, everytime it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.

    – Nirav Kotecha
    Mar 27 at 5:10











  • Thanks.That was my issues. I need to create a NSMutableDictionary into loop. @NiravKotecha

    – Josué H.
    Mar 27 at 5:15

















0















I need to add NSDictionary into NSMutableArray.



First I have created a NSMutableDictionary with a key value from other structure like this:



for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



selectedFiltersByUser is a Dictionary like this:




category_id = "XXX";
sort = "last_updated_asc";
status = "rejected_by_seller";



and for each key:value in this Dictionary I create a new NSMutableDictionary like this:




key: category_id,
value: XXX



And this new NSMutableDictionary added into NSMutableArray like this:



 for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



But when adding this NSMutableDictionary into NSMutableArray it doesn't replace the last object and I get this in query_params:



 
key: category_id,
value: XXX
,

key: category_id,
value: XXX
,

key: category_id,
value: XXX



I need this:




key: category_id,
value: XXX
,

key: sort,
value: last_updated_asc
,

key: status,
value: rejected_by_seller



I don't know how to replace the last object added.










share|improve this question





















  • 1





    try to [NSDictionary alloc] init] in the for loop and then add data.

    – Nirav Kotecha
    Mar 27 at 4:59











  • Into the loop? But I init out of the loop. I created a new NSMutableDictionary for each element and then added into other structure? @NiravKotecha

    – Josué H.
    Mar 27 at 5:02











  • yes into the loop.

    – Nirav Kotecha
    Mar 27 at 5:05












  • when you init out of the loop, everytime it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.

    – Nirav Kotecha
    Mar 27 at 5:10











  • Thanks.That was my issues. I need to create a NSMutableDictionary into loop. @NiravKotecha

    – Josué H.
    Mar 27 at 5:15













0












0








0


1






I need to add NSDictionary into NSMutableArray.



First I have created a NSMutableDictionary with a key value from other structure like this:



for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



selectedFiltersByUser is a Dictionary like this:




category_id = "XXX";
sort = "last_updated_asc";
status = "rejected_by_seller";



and for each key:value in this Dictionary I create a new NSMutableDictionary like this:




key: category_id,
value: XXX



And this new NSMutableDictionary added into NSMutableArray like this:



 for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



But when adding this NSMutableDictionary into NSMutableArray it doesn't replace the last object and I get this in query_params:



 
key: category_id,
value: XXX
,

key: category_id,
value: XXX
,

key: category_id,
value: XXX



I need this:




key: category_id,
value: XXX
,

key: sort,
value: last_updated_asc
,

key: status,
value: rejected_by_seller



I don't know how to replace the last object added.










share|improve this question
















I need to add NSDictionary into NSMutableArray.



First I have created a NSMutableDictionary with a key value from other structure like this:



for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



selectedFiltersByUser is a Dictionary like this:




category_id = "XXX";
sort = "last_updated_asc";
status = "rejected_by_seller";



and for each key:value in this Dictionary I create a new NSMutableDictionary like this:




key: category_id,
value: XXX



And this new NSMutableDictionary added into NSMutableArray like this:



 for (NSString *key in selectedFiltersByUser) 
[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];



But when adding this NSMutableDictionary into NSMutableArray it doesn't replace the last object and I get this in query_params:



 
key: category_id,
value: XXX
,

key: category_id,
value: XXX
,

key: category_id,
value: XXX



I need this:




key: category_id,
value: XXX
,

key: sort,
value: last_updated_asc
,

key: status,
value: rejected_by_seller



I don't know how to replace the last object added.







objective-c xcode nsmutablearray nsmutabledictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 14:24









Syed Ali Salman

1,9892 gold badges26 silver badges43 bronze badges




1,9892 gold badges26 silver badges43 bronze badges










asked Mar 27 at 4:51









Josué H.Josué H.

6893 gold badges11 silver badges29 bronze badges




6893 gold badges11 silver badges29 bronze badges










  • 1





    try to [NSDictionary alloc] init] in the for loop and then add data.

    – Nirav Kotecha
    Mar 27 at 4:59











  • Into the loop? But I init out of the loop. I created a new NSMutableDictionary for each element and then added into other structure? @NiravKotecha

    – Josué H.
    Mar 27 at 5:02











  • yes into the loop.

    – Nirav Kotecha
    Mar 27 at 5:05












  • when you init out of the loop, everytime it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.

    – Nirav Kotecha
    Mar 27 at 5:10











  • Thanks.That was my issues. I need to create a NSMutableDictionary into loop. @NiravKotecha

    – Josué H.
    Mar 27 at 5:15












  • 1





    try to [NSDictionary alloc] init] in the for loop and then add data.

    – Nirav Kotecha
    Mar 27 at 4:59











  • Into the loop? But I init out of the loop. I created a new NSMutableDictionary for each element and then added into other structure? @NiravKotecha

    – Josué H.
    Mar 27 at 5:02











  • yes into the loop.

    – Nirav Kotecha
    Mar 27 at 5:05












  • when you init out of the loop, everytime it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.

    – Nirav Kotecha
    Mar 27 at 5:10











  • Thanks.That was my issues. I need to create a NSMutableDictionary into loop. @NiravKotecha

    – Josué H.
    Mar 27 at 5:15







1




1





try to [NSDictionary alloc] init] in the for loop and then add data.

– Nirav Kotecha
Mar 27 at 4:59





try to [NSDictionary alloc] init] in the for loop and then add data.

– Nirav Kotecha
Mar 27 at 4:59













Into the loop? But I init out of the loop. I created a new NSMutableDictionary for each element and then added into other structure? @NiravKotecha

– Josué H.
Mar 27 at 5:02





Into the loop? But I init out of the loop. I created a new NSMutableDictionary for each element and then added into other structure? @NiravKotecha

– Josué H.
Mar 27 at 5:02













yes into the loop.

– Nirav Kotecha
Mar 27 at 5:05






yes into the loop.

– Nirav Kotecha
Mar 27 at 5:05














when you init out of the loop, everytime it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.

– Nirav Kotecha
Mar 27 at 5:10





when you init out of the loop, everytime it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.

– Nirav Kotecha
Mar 27 at 5:10













Thanks.That was my issues. I need to create a NSMutableDictionary into loop. @NiravKotecha

– Josué H.
Mar 27 at 5:15





Thanks.That was my issues. I need to create a NSMutableDictionary into loop. @NiravKotecha

– Josué H.
Mar 27 at 5:15












3 Answers
3






active

oldest

votes


















1














try to [NSMutableDictionary alloc] init] in the for loop and then add data.



because when you init out of the loop, Every time it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.



for (NSString *key in selectedFiltersByUser) 

//INIT HERE YOUR DICTIONARY
NSMutableDictionary *filters_data = [NSMutableDictionary alloc] init];

[filters_data setObject:key forKey:@"key"];
[filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

// Added filter selected id's into Array for all query_params
[query_params addObject:filters_data];






share|improve this answer
































    0














    Adding a dictionary to the array does not copy the dictionary. It store a reference to the object (dictionary) to the array, so a reference to the identical dictionary is added every time.



    Overwriting the contents of the dictionary changes the identical dictionary, which is stored multiple times in the array.



    You have to create a new dictionary every time. There is no reason to create a mutable one.






    share|improve this answer
































      0














      As the comments have pointed out your issue is due to the reference semantics of Objective-C collections, i.e. they contain references to existing objects and not copies of them. So if you add the same NSMutableDictionary multiple times to an NSMutableArray as your code does you end up with every element of the array being a reference to the same dictionary. The simple fix already suggested is to allocate the dictionary inside your loop:



      for (NSString *key in selectedFiltersByUser)

      NSMutableDictionary *filters_date = [NSMutableDictionary new];
      [filters_data setObject:key forKey:@"key"];
      [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];
      [query_params addObject:filters_data];



      However you can make it simpler and avoid the problem altogether. You are already indexing selectedFiltersByUser, you can also index filters_data in a similar way giving you:



      for (NSString *key in selectedFiltersByUser)

      NSMutableDictionary *filters_date = [NSMutableDictionary new];
      filters_data[@"key"] = key;
      filters_data[@"value"] = selectedFiltersByUser[key];
      [query_params addObject:filters_data];



      but that still leaves you with the allocation, which you can remove by using a dictionary literal:



      for (NSString *key in selectedFiltersByUser)

      NSDictionary *filters_date
      = @ @"key": key,
      @"value": selectedFiltersByUser[key]
      ;
      [query_params addObject:filters_data];



      Now there the allocation is handled automatically by the compiler and you get an NSDictionary. The final option is to drop filters_date altogether:



      for (NSString *key in selectedFiltersByUser)

      [query_params addObject:@ @"key": key,
      @"value": selectedFiltersByUser[key]

      ];



      You may find that using dictionary (and array) literals helps you avoid allocation mistakes and creating mutable structures when they are not required. HTH






      share|improve this answer



























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55370008%2fwhen-i-try-add-nsdictionary-into-nsmutablearray-i-cant-replace-the-last-object%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        try to [NSMutableDictionary alloc] init] in the for loop and then add data.



        because when you init out of the loop, Every time it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.



        for (NSString *key in selectedFiltersByUser) 

        //INIT HERE YOUR DICTIONARY
        NSMutableDictionary *filters_data = [NSMutableDictionary alloc] init];

        [filters_data setObject:key forKey:@"key"];
        [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

        // Added filter selected id's into Array for all query_params
        [query_params addObject:filters_data];






        share|improve this answer





























          1














          try to [NSMutableDictionary alloc] init] in the for loop and then add data.



          because when you init out of the loop, Every time it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.



          for (NSString *key in selectedFiltersByUser) 

          //INIT HERE YOUR DICTIONARY
          NSMutableDictionary *filters_data = [NSMutableDictionary alloc] init];

          [filters_data setObject:key forKey:@"key"];
          [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

          // Added filter selected id's into Array for all query_params
          [query_params addObject:filters_data];






          share|improve this answer



























            1












            1








            1







            try to [NSMutableDictionary alloc] init] in the for loop and then add data.



            because when you init out of the loop, Every time it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.



            for (NSString *key in selectedFiltersByUser) 

            //INIT HERE YOUR DICTIONARY
            NSMutableDictionary *filters_data = [NSMutableDictionary alloc] init];

            [filters_data setObject:key forKey:@"key"];
            [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

            // Added filter selected id's into Array for all query_params
            [query_params addObject:filters_data];






            share|improve this answer













            try to [NSMutableDictionary alloc] init] in the for loop and then add data.



            because when you init out of the loop, Every time it will go to inside loop and key is same so it will overwrite with new value. if you init into the loop it will create new one.



            for (NSString *key in selectedFiltersByUser) 

            //INIT HERE YOUR DICTIONARY
            NSMutableDictionary *filters_data = [NSMutableDictionary alloc] init];

            [filters_data setObject:key forKey:@"key"];
            [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

            // Added filter selected id's into Array for all query_params
            [query_params addObject:filters_data];







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 5:21









            Nirav KotechaNirav Kotecha

            1,8801 gold badge8 silver badges22 bronze badges




            1,8801 gold badge8 silver badges22 bronze badges


























                0














                Adding a dictionary to the array does not copy the dictionary. It store a reference to the object (dictionary) to the array, so a reference to the identical dictionary is added every time.



                Overwriting the contents of the dictionary changes the identical dictionary, which is stored multiple times in the array.



                You have to create a new dictionary every time. There is no reason to create a mutable one.






                share|improve this answer





























                  0














                  Adding a dictionary to the array does not copy the dictionary. It store a reference to the object (dictionary) to the array, so a reference to the identical dictionary is added every time.



                  Overwriting the contents of the dictionary changes the identical dictionary, which is stored multiple times in the array.



                  You have to create a new dictionary every time. There is no reason to create a mutable one.






                  share|improve this answer



























                    0












                    0








                    0







                    Adding a dictionary to the array does not copy the dictionary. It store a reference to the object (dictionary) to the array, so a reference to the identical dictionary is added every time.



                    Overwriting the contents of the dictionary changes the identical dictionary, which is stored multiple times in the array.



                    You have to create a new dictionary every time. There is no reason to create a mutable one.






                    share|improve this answer













                    Adding a dictionary to the array does not copy the dictionary. It store a reference to the object (dictionary) to the array, so a reference to the identical dictionary is added every time.



                    Overwriting the contents of the dictionary changes the identical dictionary, which is stored multiple times in the array.



                    You have to create a new dictionary every time. There is no reason to create a mutable one.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 27 at 6:19









                    Amin Negm-AwadAmin Negm-Awad

                    15.1k3 gold badges27 silver badges47 bronze badges




                    15.1k3 gold badges27 silver badges47 bronze badges
























                        0














                        As the comments have pointed out your issue is due to the reference semantics of Objective-C collections, i.e. they contain references to existing objects and not copies of them. So if you add the same NSMutableDictionary multiple times to an NSMutableArray as your code does you end up with every element of the array being a reference to the same dictionary. The simple fix already suggested is to allocate the dictionary inside your loop:



                        for (NSString *key in selectedFiltersByUser)

                        NSMutableDictionary *filters_date = [NSMutableDictionary new];
                        [filters_data setObject:key forKey:@"key"];
                        [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];
                        [query_params addObject:filters_data];



                        However you can make it simpler and avoid the problem altogether. You are already indexing selectedFiltersByUser, you can also index filters_data in a similar way giving you:



                        for (NSString *key in selectedFiltersByUser)

                        NSMutableDictionary *filters_date = [NSMutableDictionary new];
                        filters_data[@"key"] = key;
                        filters_data[@"value"] = selectedFiltersByUser[key];
                        [query_params addObject:filters_data];



                        but that still leaves you with the allocation, which you can remove by using a dictionary literal:



                        for (NSString *key in selectedFiltersByUser)

                        NSDictionary *filters_date
                        = @ @"key": key,
                        @"value": selectedFiltersByUser[key]
                        ;
                        [query_params addObject:filters_data];



                        Now there the allocation is handled automatically by the compiler and you get an NSDictionary. The final option is to drop filters_date altogether:



                        for (NSString *key in selectedFiltersByUser)

                        [query_params addObject:@ @"key": key,
                        @"value": selectedFiltersByUser[key]

                        ];



                        You may find that using dictionary (and array) literals helps you avoid allocation mistakes and creating mutable structures when they are not required. HTH






                        share|improve this answer





























                          0














                          As the comments have pointed out your issue is due to the reference semantics of Objective-C collections, i.e. they contain references to existing objects and not copies of them. So if you add the same NSMutableDictionary multiple times to an NSMutableArray as your code does you end up with every element of the array being a reference to the same dictionary. The simple fix already suggested is to allocate the dictionary inside your loop:



                          for (NSString *key in selectedFiltersByUser)

                          NSMutableDictionary *filters_date = [NSMutableDictionary new];
                          [filters_data setObject:key forKey:@"key"];
                          [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];
                          [query_params addObject:filters_data];



                          However you can make it simpler and avoid the problem altogether. You are already indexing selectedFiltersByUser, you can also index filters_data in a similar way giving you:



                          for (NSString *key in selectedFiltersByUser)

                          NSMutableDictionary *filters_date = [NSMutableDictionary new];
                          filters_data[@"key"] = key;
                          filters_data[@"value"] = selectedFiltersByUser[key];
                          [query_params addObject:filters_data];



                          but that still leaves you with the allocation, which you can remove by using a dictionary literal:



                          for (NSString *key in selectedFiltersByUser)

                          NSDictionary *filters_date
                          = @ @"key": key,
                          @"value": selectedFiltersByUser[key]
                          ;
                          [query_params addObject:filters_data];



                          Now there the allocation is handled automatically by the compiler and you get an NSDictionary. The final option is to drop filters_date altogether:



                          for (NSString *key in selectedFiltersByUser)

                          [query_params addObject:@ @"key": key,
                          @"value": selectedFiltersByUser[key]

                          ];



                          You may find that using dictionary (and array) literals helps you avoid allocation mistakes and creating mutable structures when they are not required. HTH






                          share|improve this answer



























                            0












                            0








                            0







                            As the comments have pointed out your issue is due to the reference semantics of Objective-C collections, i.e. they contain references to existing objects and not copies of them. So if you add the same NSMutableDictionary multiple times to an NSMutableArray as your code does you end up with every element of the array being a reference to the same dictionary. The simple fix already suggested is to allocate the dictionary inside your loop:



                            for (NSString *key in selectedFiltersByUser)

                            NSMutableDictionary *filters_date = [NSMutableDictionary new];
                            [filters_data setObject:key forKey:@"key"];
                            [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];
                            [query_params addObject:filters_data];



                            However you can make it simpler and avoid the problem altogether. You are already indexing selectedFiltersByUser, you can also index filters_data in a similar way giving you:



                            for (NSString *key in selectedFiltersByUser)

                            NSMutableDictionary *filters_date = [NSMutableDictionary new];
                            filters_data[@"key"] = key;
                            filters_data[@"value"] = selectedFiltersByUser[key];
                            [query_params addObject:filters_data];



                            but that still leaves you with the allocation, which you can remove by using a dictionary literal:



                            for (NSString *key in selectedFiltersByUser)

                            NSDictionary *filters_date
                            = @ @"key": key,
                            @"value": selectedFiltersByUser[key]
                            ;
                            [query_params addObject:filters_data];



                            Now there the allocation is handled automatically by the compiler and you get an NSDictionary. The final option is to drop filters_date altogether:



                            for (NSString *key in selectedFiltersByUser)

                            [query_params addObject:@ @"key": key,
                            @"value": selectedFiltersByUser[key]

                            ];



                            You may find that using dictionary (and array) literals helps you avoid allocation mistakes and creating mutable structures when they are not required. HTH






                            share|improve this answer













                            As the comments have pointed out your issue is due to the reference semantics of Objective-C collections, i.e. they contain references to existing objects and not copies of them. So if you add the same NSMutableDictionary multiple times to an NSMutableArray as your code does you end up with every element of the array being a reference to the same dictionary. The simple fix already suggested is to allocate the dictionary inside your loop:



                            for (NSString *key in selectedFiltersByUser)

                            NSMutableDictionary *filters_date = [NSMutableDictionary new];
                            [filters_data setObject:key forKey:@"key"];
                            [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];
                            [query_params addObject:filters_data];



                            However you can make it simpler and avoid the problem altogether. You are already indexing selectedFiltersByUser, you can also index filters_data in a similar way giving you:



                            for (NSString *key in selectedFiltersByUser)

                            NSMutableDictionary *filters_date = [NSMutableDictionary new];
                            filters_data[@"key"] = key;
                            filters_data[@"value"] = selectedFiltersByUser[key];
                            [query_params addObject:filters_data];



                            but that still leaves you with the allocation, which you can remove by using a dictionary literal:



                            for (NSString *key in selectedFiltersByUser)

                            NSDictionary *filters_date
                            = @ @"key": key,
                            @"value": selectedFiltersByUser[key]
                            ;
                            [query_params addObject:filters_data];



                            Now there the allocation is handled automatically by the compiler and you get an NSDictionary. The final option is to drop filters_date altogether:



                            for (NSString *key in selectedFiltersByUser)

                            [query_params addObject:@ @"key": key,
                            @"value": selectedFiltersByUser[key]

                            ];



                            You may find that using dictionary (and array) literals helps you avoid allocation mistakes and creating mutable structures when they are not required. HTH







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 28 at 17:43









                            CRDCRD

                            46.2k4 gold badges50 silver badges74 bronze badges




                            46.2k4 gold badges50 silver badges74 bronze badges






























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55370008%2fwhen-i-try-add-nsdictionary-into-nsmutablearray-i-cant-replace-the-last-object%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript