NSMutableDIctionary setObject: ForKey crashing whe

2019-09-11 00:16发布

问题:

I'm trying to use an NSMutableDictionary to pair my custom classes object with a UIButton as it's key. The UIButton that is the key is also a member of the object that I want to store as the object in the NSMutableDictionary.

My Class definition looks like ths:

@interface ClassA : NSObject {
@public
    UIButton *button1;
    UIButton *button2;
    UILabel *label;
}

@property (nonatomic, retain) UIButton *button1;
@property (nonatomic, retain) UIButton *button2;
@property (nonatomic, retain) UILabel *label;
@end

And my implementation is just this:

@implementation ClassA
@synthesize button1, button2, label;
@end

The NSMutableDictionary is in another class. I define it in the implementation like this:

@interface UIClass1 : UIViewController {
    NSMutableDictionary *Dictionary;
}

-(void)DoWork;

@property (nonatomic, retain) NSMutableDictionary *Dictionary;
@end

And the part where I'm trying to set the Dictionary values is done here:

-(void)DoWork{
    Dictionary = [[NSMutableDictionary alloc] init];
    ObjectA = [[ClassA alloc] init];

    ObjectA->button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    ObjectA->button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    ObjectA->label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 20, 20, 20)] autorelease]

    /* THIS IS A TEST AND IT WORKS FINE */
    NSString *str = [[NSString alloc] initWithFormat:@"test"];
    [Dictionary setObject:obj1 forKey:str];

    /*THIS IS WHAT I WOULD ACTUALLY LIKE TO DO */
    [Dictionary setObject:Object1 forKey:ObjectA->button1];
    [Dictionary setObject:ObjectA forKey:ObjectA->button2];
}

I've followed this code through my debugger and when I get to this line:

[Dictionary setObject:Object1 forKey:ObjectA->button1];

It just crashes SIGABRT. None of my variables are nil, every object has been allocated.

Any ideas as to why I can't set the key to the button from ClassA but I can set it the the NSString I created as a test?

回答1:

The object you use as a key in an NSMutableDictionary must conform to the NSCopying protocol.

From Apple docs:

The key for value. The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol). The key must not be nil.

UIButton does not conform to NSCopying.



回答2:

Try using

forKey:[NSValue valueWithPointer:ObjectA->button1]