Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C when to declare what methods in @interface

When and what methods should be declared in the @interface section of a class? As I understand, methods that describe what your class does should be declared in the @interface section, but other "helper" methods should not be declared. Is this a correct understanding from my side?

like image 885
Peter Warbo Avatar asked Jul 01 '11 11:07

Peter Warbo


People also ask

How do you declare method in Objective-C?

An Objective-C method declaration includes the parameters as part of its name, using colons, like this: - (void)someMethodWithValue:(SomeType)value; As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.

What is @implementation in Objective-C?

As noted, the @implementation section contains the actual code for the methods you declared in the @interface section. You have to specify what type of data is to be stored in the objects of this class. That is, you have to describe the data that members of the class will contain.

What is the difference between Category & Extension?

Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.

Does Objective-C support multiple inheritance?

In keeping with its clean and simple design, Objective C does not support multiple inheritance, though features have been developed to replace some of the functionality provided by multiple inheritance (see run-time section below). The root of the Objective C class hierarchy is the Object class.


3 Answers

One way is to declare the instance methods in .h file. And, declare the private methods inside the .m, using a Category.

For example, in MyOwnClass.h file.

@interface MyOwnClass

- (void)aInstanceMethod;

@end

And, inside your MyOwnClass.m file, before the @implementation block,

@interface MyOwnClass (MyPrivateMethods)

- (void)aPrivateMethod;

@end
like image 79
EmptyStack Avatar answered Oct 16 '22 14:10

EmptyStack


You usually should add your methods to the .h file when you want an external class to have access to it (public methods).

When they're private (only used internally by the class) just put them in your .m file.

Anyway, it's just a pattern. As Objective-C works with messages, even if you don't set a method in your .h file an external file can access it, but at least your auto-complete won't show it.

like image 25
Raphael Petegrosso Avatar answered Oct 16 '22 13:10

Raphael Petegrosso


You should declare all your methods in your .h The tip from EmptyStack is nice but it's just a tip. If you don't intend to ship your binary as an SDK, you don't really need it.

Objective-C doesn't have (yet) private methods.

like image 1
teriiehina Avatar answered Oct 16 '22 12:10

teriiehina