Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to an NSDictionary

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?

like image 455
some_id Avatar asked Jul 01 '10 16:07

some_id


People also ask

How do you add value in NSMutableDictionary?

You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil). The simplified form mentioned above, usually solves problems OCLint (metric static code analysis).

What is an NSDictionary in Swift?

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.

How do I know if NSDictionary is empty?

if (myDict. count) NSLog(@"Dictionary is not empty"); else NSLog(@"Dictionary is empty"); Every number that is 0 equals to @NO . Every number that is not 0 equals to @YES .


1 Answers

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:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10]; [dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"]; 

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue]; 
like image 176
Eiko Avatar answered Sep 28 '22 04:09

Eiko