Objective-C Language NSMutableDictionary NSMutableDictionary Example

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

+ dictionaryWithCapacity:

Creates and returns a mutable dictionary, initially giving it enough allocated memory to hold a given number of entries.

NSMutableDictionary *dict =  [NSMutableDictionary dictionaryWithCapacity:1];
NSLog(@"%@",dict);

- init

Initializes a newly allocated mutable dictionary.

NSMutableDictionary *dict =  [[NSMutableDictionary alloc] init];        
NSLog(@"%@",dict);

+ dictionaryWithSharedKeySet:

Creates a mutable dictionary which is optimized for dealing with a known set of keys.

id sharedKeySet = [NSDictionary sharedKeySetForKeys:@[@"key1", @"key2"]]; // returns NSSharedKeySet
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithSharedKeySet:sharedKeySet];
dict[@"key1"] = @"Easy";
dict[@"key2"] = @"Tutorial";
//We can an object thats not in the shared keyset
dict[@"key3"] = @"Website";
NSLog(@"%@",dict);  

OUTPUT

{
    key1 = Eezy;
    key2 = Tutorials;
    key3 = Website;
}

Adding Entries to a Mutable Dictionary

- setObject:forKey:

Adds a given key-value pair to the dictionary.

NSMutableDictionary *dict =  [NSMutableDictionary dictionary];
[dict setObject:@"Easy" forKey:@"Key1"];
NSLog(@"%@",dict);

OUTPUT

{
    Key1 = Eezy;
}

- setObject:forKeyedSubscript:

Adds a given key-value pair to the dictionary.

NSMutableDictionary *dict =  [NSMutableDictionary dictionary];
[dict setObject:@"Easy" forKeyedSubscript:@"Key1"];
NSLog(@"%@",dict);  

OUTPUT { Key1 = Easy; }

    



Got any Objective-C Language Question?