The title pretty much says it all. I want to create an NSMutableDictionary where I use UIImageViews to look up boolean values. Here's what it looks like:
My .h file:
@interface ViewController : UIViewController{
UIImageView *image1;
UIImageView *image2;
NSMutableDictionary *isUseable;
}
@property (nonatomic, retain) IBOutlet UIImageView *image1;
@property (nonatomic, retain) IBOutlet UIImageView *image2;
@property (nonatomic, retain) NSMutableDictionary *isUseable;
My .m file:
@synthesize image1, image2;
@synthesize isUseable
- (void)viewDidLoad
{
isUseable = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@NO, image1,
@NO, image2,nil];
}
-(void)runEvents{
if(some condition){
[isUseable setObject:@YES forKey:(id)image1];
}
//Use it later:
if(isUseable[image1]){
//Do stuff
}
}
It compiles but when I run it I get an uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView copyWithZone:]: unrecognized selector sent to instance.
I'm guessing that the problem lies with the fact that the NSDictionary class copies its keys. Is there a way to get a dictionary working in this case? If not, how should I set up a lookup like the one I want? Any ideas / suggestions?
Yes, the problem is that keys in an NSDictionary
must conform to the NSCopying
protocol and UIImage
does not.
One solution would be to give each image a unique tag. Then use the image's tag as the key (after wrapping it in an NSNumber
).
- (void)viewDidLoad {
isUseable = [ @{ @(image1.tag) : @NO, @(image2.tag) : @NO } mutableCopy];
}
-(void)runEvents {
if(some condition) {
[isUseable setObject:@YES forKey:@(image1.tag)];
}
//Use it later:
if(isUseable[@(image1.tag)]) {
//Do stuff
}
}
Just add the code to see each image's tag
property.