1

我创建了一个自定义类对象 Action ,其中三个枚举作为实例变量:

@interface Action : NSObject  <NSCopying>

@property ImageSide imageSide; //typedef enum 
@property EyeSide eyeSide; //typedef enum 
@property PointType pointType;  //typedef enum
@property int actionId;

- (id) initWithType:(int)num eyeSide:(EyeSide)eyes type:(PointType)type imageSide:(ImageSide)image;

@end

有了这个实现:

@implementation Action
@synthesize imageSide;
@synthesize eyeSide;
@synthesize pointType;
@synthesize actionId;

- (id) initWithType:(int)num eyeSide:(EyeSide)eyes type:(PointType)type imageSide:(ImageSide)image {    
    // Call superclass's initializer
    self = [super init];
    if( !self ) return nil;

    actionId = num;
    imageSide = image;
    eyeSide = eyes;
    pointType = type;

    return self;
}
@end

在我的 ViewController 中,我尝试将它作为键添加到 NSMutableDictionary 对象中,如下所示:

   Action* currentAction = [[Action alloc] initWithType:0 eyeSide:right type:eye imageSide:top];
    pointsDict = [[NSMutableDictionary alloc] initWithCapacity:20];
    [pointsDict setObject:[NSValue valueWithCGPoint:CGPointMake(touchCoordinates.x, touchCoordinates.y)] forKey:currentAction];

但是,当调用 setObject 时出现此错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Action copyWithZone:]: unrecognized selector sent to instance 

我在 SO 中查看了与此错误相关的一些答案,但似乎没有人解决这个问题,而且由于我是 iOS 开发的新手,我对此感到非常困惑。

4

2 回答 2

1

您声明您的Action类符合NSCopying协议。

所以你需要-(id)copyWithZone:(NSZone *)zone为那个类实现。

于 2012-10-11T13:44:48.050 回答
1

您在可变字典中用作键的对象必须符合此处NSCopyingApple 文档中描述的协议(因此copyWithZone:必须实现)

在您的情况下,您将对象声明为与NSCopying协议相对应,但您没有实现该方法。你需要。

希望这可以帮助

于 2012-10-11T13:46:09.493 回答