Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit from NSDictionary?

Tags:

objective-c

I have an object called Settings that inherits from NSMutableDictionary. When I try to initialize this object using

Settings *settings = [[Settings alloc] initWithContentsOfFile: @"someFile"]

it returns an object of type NSCFDictionary. As a result, it doesn't recognize my additional methods. For example, when I call the selector "save", it objects:

[NSCFDictionary save]: unrecognized selector sent to instance 0x524bc0

Of course, it's OK when I initialize using the garden variety

Settings *settings = [[Settings alloc] init]

I tried to cast it again to Settings but that didn't work. This seems really simple - what am I missing?

Thanks

like image 230
farhadf Avatar asked Jul 28 '09 00:07

farhadf


People also ask

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.

What is NSDictionary in Swift?

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

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).

What is NSMutableDictionary in Swift?

The NSMutableDictionary class declares the programmatic interface to objects that manage mutable associations of keys and values. It adds modification operations to the basic operations it inherits from NSDictionary . NSMutableDictionary is “toll-free bridged” with its Core Foundation counterpart, CFMutableDictionary .


1 Answers

NSDictionary is a class cluster. This means that the value returned from its init methods is not strictly an NSDictionary, but a subclass that implements the actual functionality. In almost every case, it is better to give your class an NSDictionary as an instance variable or to simply define a category on NSDictionary.

like image 96
Chuck Avatar answered Oct 23 '22 22:10

Chuck