Search code examples
iosobjective-cnsdictionarynsmutabledictionary

Add Values to existing NSDictionary From a method


I'm trying to work on the key pair: value of an NSDictionary. I need to be able to add other key: value to this NSDictionary from another method. In Swift there is dictionary.forEach ({values [$ 0] = $ 1}) but I do not know how to do it for objective C. Can you give me an example of how to insert other values from another method into an existing NSDictionary?

NSDictionary *dictionary = @{
                             kMessageFromID : currentUserID,
                             kMessageToID : recipientID,
                             kMessageTimeStamp : [NSNumber numberWithInteger:NSDate.new.timeIntervalSince1970],

                             };

Solution

  • NSMutableDictionary has a method to merge key value pairs from another dictionary.

    - (void)addEntriesFromDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary;

    You can also do fast enumeration on an NSDictionary which is comparable to forEach method of Swift.Dictionary

    NSMutableDictionary *mutableDict = ...;
    
    for (NSString *key in dictionary) {
        id value = dictionary[key];
        mutableDict[key] = value;
    }