user1146115
user1146115

Reputation: 73

Can we not declare methods in the header files?

I am watching the Stanford University iPad and iPhone application Developments course video. The instructor says in the video we can control-drag an UI object to the implementation files to create an action. But in this way the method will not declare in the header file. Does this mean it is ok to implement methods in the .m file but not declare in the .h file?

Upvotes: 7

Views: 6951

Answers (3)

CRD
CRD

Reputation: 53000

Depends on how you define "ok" :-)

Objective-C uses dynamic method lookup and does not really enforce access ("private", "public", etc.) specifiers. So you don't need to declare any method in a header file.

However you will end up fighting the compiler as it does do a fair amount of type-checking unless you persuade it not to, and you'll lose by doing so.

Upvotes: 6

mattjgalloway
mattjgalloway

Reputation: 34912

It's "OK" to not declare methods in the header yes, under certain circumstances. For instance, if using ARC then the compiler generally needs to know the method signature so it can do the right thing. But basically all it means is that wherever you're using the method, it must already know about the method you're calling.

Since you're talking about Interface Builder, that's slightly different in that it will know about all methods since it can "see" the whole context of your header and implementation files and know that a method exists. i.e. in my terminology above, the method has been defined before it's used.

With regard to defining before use, the general accepted approach is to either:

  1. Define a method in the interface file (.h). e.g.:

    MyClass.h

    @interface MyClass : NSObject
    - (void)someMethod;
    @end
    

    MyClass.m

    @implementation MyClass
    - (void)someMethod {
        // do something
    }
    @end
    
  2. Define a method in a class continuation category. e.g.:

    MyClass.h

    @interface MyClass : NSObject
    @end
    

    MyClass.m

    @interface MyClass ()
    - (void)someMethod;
    @end
    
    @implementation MyClass
    - (void)someMethod {
        // do something
    }
    @end
    

Upvotes: 5

Hot Licks
Hot Licks

Reputation: 47729

You are not required to declare in the header file all methods in the implementation. But if not in the header file obviously you cannot reference them by literal name in another file, nor can you "forward reference" them in the implementation file.

(Note that this is not that different from regular C, but is different from methods of a class in C++.)

Upvotes: 5

Related Questions