From XCode 4.2 to 4.3, new ViewController class .m

2019-05-30 08:55发布

问题:

Like most, I recently downloaded the latest version of XCode (4.3.1). I've noticed that as I'm creating new UIViewController objects, the associated .m files contain additional class definition code that I haven't ever seen before.

Specifically, if I create a new UIViewController named 'TestViewController', I get the following .m file output.

\\... removed comments...
#import "TestViewController.h"

@interface TestViewController ()

@end

@implementation TestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

\etc...

The newly added code since XCode 4.3 is the portion under the #import statement:

@interface TestViewController ()

@end

What is the purpose this code? Can/should anything go within the parenthesis? Should any code go within the @interface and @end statements?

In short, what was the point of adding this code to the template? As an interesting side note, when I tried creating an NSObject from a template, the above mentioned snippet of code wasn't added. It might appear with other types class templates but at the moment I've only encountered it with UIViewController and UITableViewController objects.

回答1:

That is an Objective-C class extension. It's used to define "private" variables, properties, and methods.

The idea is that the .h file should only contain publicly accessible properties and methods. Very often, when writing a view controller, there are methods that you will want/need to write, but these methods shouldn't be publicly visible (i.e., these methods should only be used in your .m file). You declare these methods in the class extension to keep it out of the public .h interface.



回答2:

That's a class extension and there's a good article on their uses here.



回答3:

That is just a class extension to "hide" the properties/methods declaration from the header file within the implementation file, for more info see the reference. You don't have to use it but you'll find it very convenient created automatically.