[MyClassName copyWithZone:]: unrecognized selector sent to instance?

4.2k Views Asked by At

I just implemented my class

@interface ExampleNestedTablesViewController ()
{
    NSMutableArray *projectModelArray;
    NSMutableDictionary *sectionContentDictionary;

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    ProjectModel *project1 = [[ProjectModel alloc] init];
    project1.projectName = @"Project 1";

    ProjectModel *project2 = [[ProjectModel alloc] init];
    project2.projectName = @"Project 2";
    if (!projectModelArray)
    {
        projectModelArray = [NSMutableArray arrayWithObjects:project1, project2, nil];
    }

    if (!sectionContentDictionary)
    {
        sectionContentDictionary  = [[NSMutableDictionary alloc] init];

        NSMutableArray *array1     = [NSMutableArray arrayWithObjects:@"Task 1", @"Task 2", nil];
        [sectionContentDictionary setValue:array1 forKey:[projectModelArray objectAtIndex:0]]; // **this line crashed**.

    }
}

Here is my Project Model

@interface ProjectModel : NSObject

typedef enum
{
    ProjectWorking = 0,
    ProjectDelayed,
    ProjectSuspended,

} ProjectStatus;

@property (nonatomic, assign) NSInteger idProject;
@property (nonatomic, strong) NSString* projectName;
@property (nonatomic, strong) NSMutableArray* listStaff;
@property (nonatomic, strong) NSTimer* projectTimer;
@property (nonatomic, assign) ProjectStatus projectStatus;
@property (nonatomic, strong) NSMutableArray* listTask;
@property (nonatomic, assign) NSInteger limitPurchase;
@property (nonatomic, strong) NSDate* limitTime;
@end

And the output is: SDNestedTablesExample[1027:c07] -[ProjectModel copyWithZone:]: unrecognized selector sent to instance 0x7562920. I didn't know which problem. Can you help me ?

1

There are 1 best solutions below

0
On

Look at the docs for NSMutableDictionary setObject:forKey: (note you should use setObject:forKey:, not setValue:forKey:). Notice the expected type for the key. It must be of type id<NSCopying>. This means the key must conform to the NSCopying protocol.

Since your keys are of type ProjectModel, the error is complaining since your ProjectModel class doesn't implement the required method of the NSCopying protocol - copyWithZone:.

Are you sure you want to use a ProjectModel object as the key? Doing so also means you need a sane implementation of the isEqual: and hash methods, in addition to copyWithZone.

The solution is to update your ProjectModel class so it conforms to the NSCopying protocol and implements the copyWithZone: method. And also properly implement the isEqual: and hash methods. Or change the key to be just the idProject property (properly wrapped as an NSNumber).