John R Doner
John R Doner

Reputation: 2282

Redundant Compiler Warnings

I have found that very often, when calling myMethod asoociated with myObject1 from myObject2, I get the warning that "myObject1 may not respond to -myMethod", but then the program runs just fine anyway. Why doesn't the compiler recognize declared methods at compile time?

John Doner

Upvotes: 2

Views: 169

Answers (5)

Quinn Taylor
Quinn Taylor

Reputation: 44769

One case where this happens frequently is if the type of the variable that contains the object is that of a superclass, and the method is only defined for the subclass. You can avoid this by either typing it as id or making the static typing more specific. If the variable type is that of the class itself, it's likely that the method isn't visible to the compiler in the scope where you're trying to invoke it — the other answers deal with this situation.

Upvotes: 0

Elise van Looij
Elise van Looij

Reputation: 4232

Usually, adding

@class myObject1

will solve the problem. Check out Ben Gottlieb's answer to Objective-C @class vs. #import here on Stack Overflow.

Upvotes: -2

Darren
Darren

Reputation: 25619

The warning means you're calling a method for which the compiler has not yet seen a method declaration. It is an error in most other languages, and it is certainly a warning you cannot ignore.

If you haven't declared the method, do so in an @interface block at the top of your source file (if it's a private method) or in your class's header file (if it's a public method).

If you have declared the method in a header file, be sure to import the header file.

If you have declared the method and you are importing the correct header file, you have a typo somewhere.

Upvotes: 1

RyanWilcox
RyanWilcox

Reputation: 13972

Or sometimes, if you're using a delegate class, you need to define a category with those delegate methods in order for the compiler to find them.

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243156

This shows up as a warning because Objective-C is a very dynamic language. At compile time, the compiler hasn't found the declaration for "myMethod" (perhaps you're missing a header file, or forgot to include it in the header?) when it was attempting to compile the file. However, it only generated a warning because Objective-C has the ability to create and load extra methods at runtime so that by the time that code executes, that method will exist. Hence, it is only a warning.

Most likely you just haven't declare the method in the appropriate header file.

Upvotes: 2

Related Questions