NSDictionary: Store 3 float values for every key
how can I do this? Basically I want to store RGB color values that can be retrieved in response to a color name. My C++ code uses boost unordered_map to do this:
("SlateBlue1", Color(0.5137f, 0.4353f,1.0f))
("tan3", Color(0.8039f, 0.5216f, 0.2471f))
("grey32", Color(0.3216f, 0.3216f, 0.3216f))
Color is a class that stores the 3 value开发者_如何学JAVAs. Trying to do this in Objective-C is tying me up in knots and weird errors! Most of the dictionary examples I've found are simply matching 2 strings. Of course I can just use the C++ code in a .mm file, but if anyone has any ideas how to achieve this the Obj-C way, I'd be pleased to learn, thanks.
It's exactly the same in Cocoa - use a NSDictionary instead of the unordered_map, NSString instead of const char* for the key and UIColor instead of Color for the object and you're done.
E.g., [NSDictionary dictionaryWithObject: [UIColor redColor] forKey: @"Red"]]
to create a single-entry map. Adjust for multiple colors and you're all set. Use NSColor if you're not on iOS.
You might be missing the key point that a dictionary is an (almost) untyped collection, so it can store a heterogenous set of object types using a heterogenous set of key types.
If you're color object extends NSObject, you should be able to store those colors as the values in your NSDictionary
.
NSDictionary *colors = [[NSDictionary alloc] initWithObjectsAndKeys:Color1, @"SlateBlue1", Color2, @"tan3", Color3, @"grey32", nil ];
That should work and then you'd use
Color *mycolor = [colors objectForKey:@"SlateBlue1"];
And then access your colors from your object.
Also, not sure of the purpose of your color object but you could use NSColor
for Cocoa or UIColor
for Cocoa-touch to store these as well.
(I haven't tested this code, just wrote from memory)
If you want to use a UIColor
object or similar, the other answers cover it. If you really want to store three floats, you have a couple of options. You can store an NSArray of three NSNumbers for each triple of floats:
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObjects:[NSNumber numberWithFloat:.5], [NSNumber numberWithFloat:.7], [NSNumber numberWithFloat:.2], nil], @"bleem",
... // more array/string pairs
nil];
Or you can use an NSData
for each triple of floats:
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
[NSData dataWithBytes:&(float[]){ .5, .7, .2} length:3*sizeof(float)], @"bleem",
... // more data/string pairs
nil];
精彩评论