Search code examples
objective-cxcodecocoagenerated-code

Multiple @interface declarations generated by Xcode for NSViewController?


I am making a Cocoa application, and using Xcode for various code-generation. Works fine for generating .h and .m files for subclassing UIView, but when i subclass UIViewController i get an @interface declaration identical in both files, except that in the .m file it has ( ) at the end:

//in MyViewController.h
@interface MyViewController : NSViewController <MyViewDelegate>

@end

but also

//in MyViewController.m
@interface MyViewController ()

@end

@implementation MyViewController

@end

Yet it compiles fine. So, assuming this is normal behavior, the two-parts of question are: (A) Why does this happen, and (B) What are the results -- especially in terms of compile order?

Thanks!


Solution

  • when i subclass UIViewController i get an @interface declaration identical in both files, except that in the .m file it has ( )

    As you noticed, the two interface blocks are not identical -- the () is important. The one with the () is a class extension, which is similar to a category without a name. The two important differences between a category and a class extension are:

    1. You can declare instance variables in a class extension, but you can't in a category.

    2. A class extension must appear in the same file as the implementation block.

    Class extensions are useful for declaring instance variables and methods that you don't want to expose in the header file, such as methods or variables that are specific to the implementation and shouldn't be relied upon by users of the class.