Search code examples
objective-cselectornstimer

Objective-C - NSTimer: unrecognized selector sent to class - call method from another class


addCloudOne is a method within the Food class. The following code produces a crash with the following error:

+[Food addCloudOne]: unrecognized selector sent to class 0x1000ad760

    SEL selector = @selector(addCloudOne);
    [NSTimer scheduledTimerWithTimeInterval:k1 target:[Food class] selector:selector userInfo:nil repeats:YES];

Do you have ideas?


Solution

  • You need to specify an instance of the Food class, so this argument is incorrect:

    target:[Food class]
    

    So what you are passing to NSTimer is a Class object, not a Food object.

    Instead you probably need an instance variable of the Food instance and specify that:

    @interface MyClass ()
    {
        Food *_food;
    }
    
    @implementation MyClass
    ...
    - (void)whatever
    {
        _food = [Food new];             // This might need to be elsewhere
        SEL selector = @selector(addCloudOne);
        [NSTimer scheduledTimerWithTimeInterval:k1
                                         target:_food
                                       selector:selector
                                       userInfo:nil
                                        repeats:YES];
    }