I'm trying to access my dictionary object. Here's my code:
int tag = object.tag;
CGPoint point = [[self.dict objectForKey:tag] CGPointValue];
The problem is objectForKey is supposed to take an Objective-C object, not an int. I tried wrapping tag into an NSNumber with [NSNumber numberWithInt:tag]
and passing that into objectForKey:
but it returns a null object.
Any ideas? Thanks
You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.
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.
NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both.
I use NSNumbers without problems, but must avoid the usual setObject: forKey:
or setValue: forKey:
methods. That would create a warning.
No warning, however, is created (and the code works as intended) with
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
NSNumber *key = @1;
id *myObject = [your code here];
myDict[key] = myObject;
Retrieval is straightforward:
myObject = myDict[key];
If you are using numbers as strings for dictionary keys, you should turn the int
into a NSString
or NSNumber
to use it as a dictionary key. Here's how to do it for a string:
NSString *key = [NSString stringWithFormat:@"%d", myInteger];
As @Hughes BR mentions in a comment, the requirement for the key object is that it must conform to the NSCopying
protocol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With