IOS, NSMutableDictionary

I had a problem in my project where I declared the NSMutableDictionary property in the header file as follows:

@property (copy, nonatomic) NSMutableDictionary *DataDict ; 

Now, in the implementation file, I continue and initialize this dictionary, because I will use it, for example:

 DataDict = [[NSMutableDictionary alloc]init]; 

Now that I have done this, the minute I try to add something to this dictionary, I would get an error message:

- [__ NSDictionaryI setObject: forKey:]: unrecognized selector sent to instance 0x885ae60 2012-10-19 16: 51: 56.040 testing [2297: c07] * Application terminated due to an uncaught exception 'NSInvalidArgumentException', reason: '- [__ NSDictionaryI setObject: forKey:]: unrecognized selector sent to instance 0x885ae60 '

After some time and through my project a thousand times, I decided to uncomment my initialization line, for example:

  //DataDict = [[NSMutableDictionary alloc]init]; 

and this fixed the problem.

My question is why?

+6
source share
2 answers

The problem is how you defined your property. If you change it to:

 @property (strong, nonatomic) NSMutableDictionary *DataDict ; 

instead of copy everything should be fine.

This is because you basically say that you want to get a copy of your object through the generated accessors, which instead returns an NSDictionary (immutable copy).

More information about objective-c properties can be found here .

Just like a side element: objective-c ivars usually start with a lowercase letter (upper case names are used for classes), so dataDict should be preferable to dataDict .

+15
source

This is because the property has the attribute โ€œcopyโ€, so the instance of the NSMutableDictionary alloc / init-ed instance โ€œcopiesโ€ ed using the โ€œcopyโ€ method, and the โ€œcopyโ€ method creates not NSMutableDictionary, but NSDictionary. ("mutableCopy" will create an NSMutableDictionary).

Perhaps you can use โ€œsaveโ€ instead of โ€œcopyโ€ as attributes.

 @property (retain, nonatomic) NSMutableDictionary *DataDict ; 

Or just without copy / save, but use ARC. (Automatic reference counting).

+2
source

Source: https://habr.com/ru/post/928154/


All Articles