在删除UIKit.h的导入后,为什么可以引用UIKit类?

时间:2012-05-06 22:20:14

标签: objective-c cocoa-touch import header-files

我一直在观看视频,声明UIAlertView只有在导入UIKit.h时才有效。但是,如果我在头文件中注释掉import语句:

//#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

当我将其添加到实现文件时,警报仍然有效:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}

请解释为什么这有效? UIKit的真正作用是什么?

2 个答案:

答案 0 :(得分:8)

这是因为它可能已在您的Prefix.pch文件中声明,默认情况下看起来像这样:

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
#endif

答案 1 :(得分:3)

UIKit.h只是定义类等的文件。

没有它,编译器就不会知道UIAlertView是什么。

但是,在您的情况下它可能仍然有效,因为#import <UIKit/UIKit.h>通常包含在项目的前缀文件中,默认情况下包含在您的源中。