4

Sorry for my English, let speak from my heart :) In one project which I work, I noticed an interesting moment.

In *.h file declared interface:

@interface FrontViewController : UIViewController
...
@end

And in *.m file I found another interface.

@interface FrontViewController()

// Private Properties:
@property (retain, nonatomic) UIPanGestureRecognizer *navigationBarPanGestureRecognizer;

// Private Methods:
- (IBAction)pushExample:(id)sender;

@end

@implementation FrontViewController
...
@end

Why is it needed? And what's the point? -I think that this is for convenience. Yes?

edc1591
  • 10,146
  • 6
  • 40
  • 63
Ilya Ilin
  • 2,283
  • 21
  • 27
  • Because I programmed in ObjectiveC++ and C++ also has head files and implementation files. – Ilya Ilin Mar 06 '12 at 20:06
  • 1
    This has been answered many times. Here's one: [Difference between @interface definition in .h and .m file](http://stackoverflow.com/questions/3967187/difference-between-interface-definition-in-h-and-m-file) – jscs Mar 06 '12 at 20:09
  • Sorry, I don't find before post question. – Ilya Ilin Mar 06 '12 at 20:15

2 Answers2

6

That's a class extension. It's usually used to declare private methods and properties for a class.

Read about it here.

edc1591
  • 10,146
  • 6
  • 40
  • 63
  • Hmm, except I can not specify private methods in an .h file? Or if I specify in .m file private methods, I get additional plus in check on compilation for implement privite methods specified in .m file? – Ilya Ilin Mar 06 '12 at 20:32
  • The header is the publicly available class definition. – N_A Mar 06 '12 at 21:35
3

That is a class extension. It allows you to declare "private" methods and properties for a class, even if you don't have access to the source. The primary use is to not expose those methods as part of the interface. Unlike most languages, these methods are run-time discoverable, so the value of these is in the IDE auto-completion, not in preventing consumers of your class from calling the hidden methods, which is why I put private in quotes. It is possible to simply define methods in the implementation without a declaration, but then they must be implemented above any places they are used. Declaring them as an extension prevents this problem.

If an extension is named, then it becomes a category which can be used to distribute your class implementation among several files.

N_A
  • 19,799
  • 4
  • 52
  • 98