Xcode - 实现一个方法,也可以由它的主类实现

Rea*_*ion 2 objective-c pragma

我正在使用Xcode 4.5.在我最新的Xcode项目中,当我构建/编译我的程序时,我会弹出这个警告:

Category is implementing a method which will also be implemented by its primary class

这是导致错误的代码:

 @implementation NSApplication (SDLApplication)
 - (void)terminate:(id)sender {
    SDL_Event event;
    event.type = SDL_QUIT;
    SDL_PushEvent(&event); }
 @end
Run Code Online (Sandbox Code Playgroud)

我已经这样做了,所以编译器忽略(或跳过)使用的警告生成pragma code.

所以我的代码现在看起来像这样:

 @implementation NSApplication (SDLApplication)

 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
 - (void)terminate:(id)sender{
   SDL_Event event;
   event.type = SDL_QUIT;
   SDL_PushEvent(&event);}
 #pragma clang diagnostic pop
 @end
Run Code Online (Sandbox Code Playgroud)

显然它完成了这项工作,一旦构建/编译,就不会产生任何警告.

我的问题是,这是一种以这种方式抑制或忽略警告的安全/可靠方式吗?

我在一些线程上读到使用子类是有利的,但是有很多人以这种方式反对使用它们...我很感激你的想法:)

NSG*_*God 5

"我在一些线程上读到使用子类是有利的......"

使用子类可能是有利的,但这不是你在这里做的.

你做了什么来实现的(SDLApplication) Objective-C的类别NSApplication.在那个类别中,你是最重要NSApplicationterminate:方法.通常,您应该仅使用类别向现有类添加其他方法,而不是覆盖现有方法,因为这可能会产生不可预测的结果.

你真正应该做的是子类,NSApplication以便你可以terminate:正确覆盖:

@interface SDLApplication : NSApplication {

}

@end


@implementation

- (void)terminate:(id)sender {
   SDL_Event event;
   event.type = SDL_QUIT;
   SDL_PushEvent(&event);
   [super terminate:sender]; // this line is the key to assuring proper behavior
}

@end
Run Code Online (Sandbox Code Playgroud)

重写terminate:方法的最后一步应该是调用super,以便terminate方法可以正常工作.(super不允许在类别中使用关键字;只允许使用单词self,这就是为什么需要子类化的原因).

确保您还要更改文件中NSPrincipalClass密钥的值而不是.Info.plistSDLApplicationNSApplication