3

According to developer documentation, a class extension is implemented by declaring an @interface in the implementation file, and it can also be used to redeclare instance variables to be private. However, I frequently see the code below that does not declare new methods or instance variables. What is its purpose?

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController 
...  
jscs
  • 63,694
  • 13
  • 151
  • 195
Pippi
  • 2,451
  • 8
  • 39
  • 59
  • 1
    Class extensions are not used to *re*declare instance variable as private. You can use the class extension to *declare* private instance variables. Which means the instance variables should never be put in the .h file. Of course it's easiest (and best) to declare instance variables in the `@implementaiton` block. – rmaddy Jan 18 '15 at 19:36

1 Answers1

4

There is no purpose behind such code. The only reason it is there is that it is part of the standard template for creating .m files in Xcode.

With this said, such class extensions are entirely harmless, so keeping them in case you need to add private methods or variables does not hurt performance of your app. In the end, it is a matter of personal taste: for example, I remove such unused template-generated artifacts from my code, but I can accept an argument in favor of keeping them as well.

If you do not wish to have these class extensions generated by default, clone and modify Xcode template for new Objective-C classes (here is a Q&A explaining how to do it).

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    I think it's better to remove any generated code that does nothing (like `viewDidLoad` or `didReceiveMemoryWarning` which only call `super`). The code is written once but read many times, so save yourself and your co-workers precious time from reading unneeded code. – Michał Ciuba Jan 18 '15 at 19:32
  • I don't think that Q&A has been right for many years. It is effectively impossible to modify the templates nowadays. – matt Jan 18 '15 at 20:18
  • @matt I'm using several custom templates (at least my own class templates) with Xcode 6 so it must still be possible. – rmaddy Jan 18 '15 at 22:43