Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add key to NSDictionary (iPhone SDK)

A really quickly trying to add a key to a .plist. I almost have it, what is the correct version of the fourth line?

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
    NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
    [rootDict addKey:@"Test"]; //guessed code
    [rootDict writeToFile:path atomically: YES];
like image 690
DexCurl Avatar asked Feb 27 '11 17:02

DexCurl


People also ask

How do you add value in NSMutableDictionary?

[myDictionary setObject:nextValue forKey:myWord]; You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

How do I create an NSDictionary in Objective C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.

What is NSMutableDictionary?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.


1 Answers

You can't add elements to a NSDictionary, you need to use a NSMutableDictionary then use the setObject:forKey: method.

[rootDict setObject:someObject forKey:@"someKey"];

See NSMutableDictionary class reference

like image 124
mmccomb Avatar answered Oct 15 '22 07:10

mmccomb