我正在尝试使用NSMutableDictionary将我的自定义类对象与UIButton配对,因为它是关键。作为键的UIButton也是我想要存储为NSMutableDictionary中对象的对象的成员。
我的班级定义如下:
@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
我的实施就是这样:
@implementation ClassA
@synthesize button1, button2, label;
@end
NSMutableDictionary在另一个类中。我在实现中定义它如下:
@interface UIClass1 : UIViewController {
NSMutableDictionary *Dictionary;
}
-(void)DoWork;
@property (nonatomic, retain) NSMutableDictionary *Dictionary;
@end
我试图设置字典值的部分在这里完成:
-(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];
}
我通过我的调试器跟踪了这段代码,当我到达这一行时:
[Dictionary setObject:Object1 forKey:ObjectA->button1];
它只会使SIGABRT崩溃。我的变量都不是零,每个对象都已分配。
为什么我不能从ClassA设置按钮键的任何想法,但我可以将它设置为我作为测试创建的NSString?
答案 0 :(得分:2)
用作NSMutableDictionary中的键的对象必须符合NSCopying协议。
来自Apple文档:
价值的关键。密钥被复制(使用copyWithZone:;密钥必须 符合NSCopying协议)。关键不能是零。
UIButton不符合NSCopying。
答案 1 :(得分:1)
尝试使用
forKey:[NSValue valueWithPointer:ObjectA->button1]