I have one NSDictionary
and it loads up UITableView
. If a user scrolls more and more, I call API and pull new data. This data is again in the form of an NSDictionary
. Is it possible to add the new NSDictionary
to the existing one?
3 Answers
You looking for this guy:
[NSMutableDictionary addEntriesFromDictionary:]
Make sure your UITableView
dictionary is an NSMutableDictionary
!
-
9Yes, but why do you want duplicate entries of keys in a dictionary? – Johan Karlsson Jul 03 '14 at 06:35
-
2What I want is `-[NSDictionary dictionaryByAddEntriesFromDictionary:]`, however, there is no such a method in `NSDictionary`. – DawnSong Dec 09 '15 at 05:52
-
Obviously, it's just dictionaries' union operation, not duplicate entries. @JohanKarlsson – DawnSong Dec 09 '15 at 05:55
-
3@DawnSong I would just create a category on NSDictionary if I were you with the following method: `+ (instancetype)dictionaryByAddingEntriesFromDictionary:(NSDictionary *)dictionary { NSMutableDictionary *combinedDictionary = [NSMutableDictionary dictionaryWithDictionary:self]; [combinedDictionary addEntriesFromDictionary:dictionary]; return combinedDictionary; }` Sorry for the formatting issues. StackOverflow doesn't allow friendly multi-line code formatting in comments. – BigSauce Apr 17 '16 at 04:53
-
I think the real question is about how to do this WITHOUT intermediate mutable objects. The main benefit for such a thing (which exists for NSString, for instance) is being thread safe. – Motti Shneor May 26 '20 at 09:57
-
If the NSMutableDictionary is only intermediate, then it does not matter if it's thread safe because you would simply return an NSDictionary after you had finished merging in another dictionary. All of the work will be done in one thread. – Kendall Helmstetter Gelner Jan 25 '23 at 07:40
Use NSMutableDictionary addEntriesFromDictionary to add the two dictionaries to a new mutable dictionary. You can then create an NSDictionary from the mutable one, but it's not usually necessary to have a dictionary non-mutable.

- 47,103
- 17
- 93
- 151
Is your NSDictionary full of other NSDictionaries? It sounds like you would need an NSMutableArray that you could add NSDictionaries to at the end. Assuming you can control the flow of data coming in and wouldn't run the risk of duplicates in your array, you could certainly append the data.
NSMutableArray *array = [[NSMutableArray alloc] init];
arrayCount = [array count]; // check the item count
[array addObject:dictToAppend];
Without seeing how you are implementing it, I can't provide more detailed code examples. Appending items is easy to do, but know it can only be done with mutable versions of Arrays or Dictionaries. Hope this helps a little.

- 14,054
- 6
- 49
- 86