Search code examples
iosnsmutabledictionary

NSMutableDictionary returning null


I created an NSMutableDictionary in NSObject class like

@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments;

and saved the data in this variable when comes through API.

But when I am sending the key to get the value it is returning null every time.

To get the value I am doing like this

NSLog(@"%@",dataManager.requestComments[serviceRequest.RequestId]);
// serviceRequest.RequestId is returning NSNumber.

the output I'm getting is "(null)"

if I use to like this then it returns a value

NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]);

Why it is returning null in the above case.


Solution

  • Based on your question, this should work

    NSLog(@"%@",dataManager.requestComments[[serviceRequest.RequestId stringValue]]);
    

    Because you gave the key as NSString and you are expecting it to return based on an NSNumber. You need to look at the code which you are using to store this dictionary.

    Update

    You have mentioned that key is of NSNumber type. But you are passing a string in valueForKey and getting a valid object back. You should check how you are forming this dictionary from API response.