views:

33

answers:

2

I have just started to develop for the iPhone and am in the process of learning Objective-C. I have seen some code that implements a method in the @implementation side of a class like this:

-(void)myMethod; { // method body }

What makes this interesting is that there is no mention of myMethod in the @interface for the class. I tried a sample project with this and when I compile I get a warning from XCode that myMethod may not be seen by the calling code.

Can anyone tell me what is going on?

Thanks!

A: 

In ObjC, method calls are resolved dynamically (dynamic binding), meaning that when you do [obj myMethod];, internally the ObjC runtime software will go through the class methods at that point in time and if it finds one called "myMethod" it will then call it.

Also it is possible to add methods to an object at runtime.

The method declarations in an @interface section is only there to help the compiler determine what methods are publicly available for a given class. If you do add a method in your @implementation only, the compiler may warn you about that, but the code will still compile and work.

I sometimes use this to add internal methods to my objects, which are only called from other methods after it, and never from outside. Though I don't remember seeing warnings about it... Make sure that the calling code is placed after the method implementation in the same file.

squelart
It may be the semicolon after the method name causing the warning. When writing unit test classes I always omit the declaration in the @interface and I never see such warnings.
JeremyP
+2  A: 

It's just like functions in C. You don't need a declaration (i.e. it doesn't have to be in the @interface) but if there's no declaration, any code before the method definition will generate that warning. Code after the method definition will not generate a warning.

Tom Dalling