I was using a NSMutableArray
and realized that using a dictionary is a lot simpler for what I am trying to achieve.
I want to save a key as a NSString
and a value as an int
in the dictionary. How is this done? Secondly, what is the difference between mutable and a normal dictionary?
When ever the array is declared, then only we have to add the key-value's in NSDictionary like
we cannot add or remove the key values in this NSDictionary
Where as in NSMutableDictionary we can add the objects after intialization of array also by using this method
for removing the key value we have to use the following code
By setting you'd use
setValue:(id)value forKey:(id)key
method ofNSMutableDictionary
object:Or in modern Objective-C:
The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of
NSMutableDictionary
(andNSMutableArray
) while you can't do that with "normal"NSDictionary
andNSArray
For reference, you can also utilize
initWithDictionary
to init theNSMutableDictionary
with a literal one:A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.
create and add:
and retrieve:
You want to ask is "what is the difference between a mutable and a non-mutable array or dictionary." Many times there different terms are used to describe things that you already know about. In this case, you can replace the term "mutable" with "dynamic." So, a mutuable dictionary or array is one that is "dynamic" and can change at runtime, whereas a non-mutable dictionary or array is one that is "static" and defined in your code and does not change at runtime (in other words, you will not be adding, deleting or possibly sorting the elements.)
As to how it is done, you are asking us to repeat the documentation here. All you need to do is to search in sample code and the Xcode documentation to see exactly how it is done. But the mutable thing threw me too when I was first learning, so I'll give you that one!
Update version
Objective-C
Create:
Change:
The short-hand syntax is called
Objective-C Literals
.Swift
Create:
Change: