开发者

Why does creating a new Objective-C class file in XCode4 not create a "An Objective-C class, with a header that includes the <Cocoa/Cocoa.h> header."

When I create a new Objective-C class file in XCode 4 it creates two files:

one whose content is:

#import <Foundation/Foundation.h>


@interface MyClass : NSObject {
@private

}

@end

and one whose content is:

#import "MyClass.h"


@implementation MyClass

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    ret开发者_StackOverflow社区urn self;
}

- (void)dealloc
{
    [super dealloc];
}

@end

I'm a beginner working out of a Dummies book, and This is not what I'm used to seeing in XCode3 when I create a new file. Plus, the wizard says the file should have a <Cocoa/Cocoa.h> in the header, but these files have Foundation.h in the header.


You are reading an old book. If you take a look Cocoa.h it is importing:

  • #import Foundation/Foundation.h
  • #import AppKit/AppKit.h
  • #import CoreData/CoreData.h

This was the standard practice for most Cocoa application on Mac OS X. Now, that we have iOS it doesn't use AppKit.framework; iOS uses UIKit.framework. So the template is only going to import Foundation.h only. This way you can use your subclass in a project that targets the Mac OS X or iOS platform. This way you don't have to write #define statements for the different platform.

If you take a look at the pre-compiled header (.pch) for a Mac OS X project it will import Cocoa.h for you which import AppKit.h. And the iOS project .pch imports UIKit.h.


By

  • Looking at Xcode Templates /Developer/Library/Xcode/Templates/File Templates
  • Especially at Cocoa templates in Cocoa/ folder

I can see that :

  • NSDocument, NSView, NSViewController, NSWindowController templates are importing Cocoa.h
  • NSObject aka the magical ___VARIABLE_cocoaSubclass___ in template is the only one importing Foundation.h

That's what you can see in interface :

Why does creating a new Objective-C class file in XCode4 not create a "An Objective-C class, with a header that includes the <Cocoa/Cocoa.h> header."

So explanation is simple, despite description of "Cocoa" templates, if you're using a Cocoa class as listed above, Cocoa.h will be imported, otherwise, Foundation.h will be.

That makes sense since templating is not smart enough to determine what should be imported, and that a good coding practice is to import the minimum possible.


In your project you have a MyProjectName-Prefix.pch file. This is your Pre-Compiled-Header file. Headers listed in here are automatically included in every other header in your project in a more efficient way (the 'pre-compiled' bit). If you open it you will see #import <Cocoa/Cocoa.h>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜