Search code examples
objective-cobjective-c-category

Accessing category method in original Objective C class


I have a class for which I have created a category. Now I want to access category method inside original class but I am getting error:

error: instance method '-hasSound' not found (return type defaults to 'id') [-Werror,-Wobjc-method-access]

// Animal.h 
@interface Animal: NSObject 
- (void)sound;
@end

// Animal.m
#import "Animal+Additions.h"
@implementation Animal
- (void)sound {
 [self hasSound];
}
@end

// Animal+Additions.h
@interface Animal (Additions) 
- (BOOL)hasSound;
@end

// Animal+Additions.h
@implementation Animal (Additions)
- (BOOL) hasSound {
   return YES;
}
@end

I have been doing same thing in Swift but not sure how to achieve the same thing in Objective C. Category and original class are in separate files. I have imported Category interface file inside original class but that didn't work.


Solution

  • You have not shown sufficient #import statements, so I have to assume they don't exist. You need them.

    Another possible issue is that, at least according to your comments, you seem to have two Animal+Additions.h files but no Animal+Additions.m file.

    This complete code in four files compiles for me:

    //  Animal.h
    
    #import <Foundation/Foundation.h>
    @interface Animal: NSObject
    - (void)sound;
    @end
    
    //  Animal.m
    
    #import "Animal.h"
    #import "Animal+Additions.h"
    @implementation Animal
    - (void)sound {
        [self hasSound];
    }
    @end
    
    // Animal+Additions.h
    
    #import "Animal.h"
    @interface Animal (Additions)
    - (BOOL)hasSound;
    @end
    
    //  Animal+Additions.m
    
    #import "Animal+Additions.h"
    @implementation Animal (Additions)
    - (BOOL) hasSound {
        return YES;
    }
    @end
    

    Note all the #import statements, and note that the Animal.m file must be part of the target.