Question

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!

Was it helpful?

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.

OTHER TIPS

Are you familiar with Categories? What you are observing is similar, but has important distinctions from Categories. The distinction here is that it is anonymous (hence the empty parens) and compiled at the same time the original class is compiled. That later part is an important part: it means you can add instance properties (storage). This is most commonly used to declare "internal only" or "private" methods and properties. But keep in mind that at runtime there is no notion of 'private' enforcement, it's all about what interface you have published vs. not published. This is just one way to have very clearly defined interface that is only 'published' to people who author the implementation file of the core class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top