views:

343

answers:

3

Hi,

I have derived from a 3rd party class, and when I attempt to call a method in the base class, I get the x may not respond to y compiler warning.

How can I remove the warning?

Repro:

@interface ThirdPartyBaseClass : NSObject {}
+(id)build;
-(void)doStuff;
@end

@implementation ThirdPartyBaseClass
+(id) build{
    return [[[self alloc] init] autorelease];
}
-(void)doStuff{ 
}
@end

@interface MyDerivedClass : ThirdPartyBaseClass {}
+(id)buildMySelf;
@end

@implementation MyDerivedClass
+(id)buildMySelf{
    self = [ThirdPartyBaseClass build];
    [self doStuff]; // compiler warning here - 'MyDerivedClass' may not respond to '+doStuff'
return self;
}
@end

Thanks!

A: 

Have you tried changing buildMySelf to:

+(id)buildMySelf{
      self = [MyDerivedClass build];
      [self doStuff];
      return self;
}

Using [ThirdPartyBaseClass build]; produces an instance of ThirdPartyBaseClass, not MyDerivedClass.

Chris Long
This still produces the 'may not respond to...' warning
zadam
+1  A: 

-(void)doStuff is an instance method, but you are calling it on what the compiler thinks is the class. The compiler believes self to be typed as as a Class, and not as a ThirdPartyBaseClass object

Try

@implementation MyDerivedClass
+(id)buildMySelf{
    id other = [ThirdPartyBaseClass build];
    [other doStuff];
    return other;
}
@end
Brandon Bodnár
+3  A: 

In a class method (preceded by the '+'), 'self' is not an instance of the class; 'self' is the Class object, which only responds to Class methods, not instance methods. If you're building an instance so you can call doStuff on it and return it, you'll need to use a separate variable:

+ (id) buildMySelf
{
   MyDerivedClass *myDerivedClassInstance;

   myDerivedClassInstance = [self build];
   [myDerivedClassInstance doStuff];

   return myDerivedClassInstance;
}
tedge