在某些情况下,Objective-C扩展会生成"可能不响应警告"

Fra*_*ank 0 cocoa objective-c ios

代码构建一个警告并生成预期输出"Hello,World!"

示例文件"TestClass.h"

#import <Cocoa/Cocoa.h>
@interface TestClass : NSObject {
}

- (void)foobar;
@end
Run Code Online (Sandbox Code Playgroud)

示例文件"TestClass.m"

#import "TestClass.h"

@implementation TestClass
- (void)say {
    // Compiler output "warning: 'TestClass' may not respond to '-hello'"
    [self hello]; 
}

- (void)hello {
    NSLog(@"Hello, World!");
}

- (void)foobar {
    [self say];
}
@end

@interface TestClass ()
- (void)say;
- (void)hello;
@end
Run Code Online (Sandbox Code Playgroud)

通过在@implementation部分中将"hello"方法置于"say"之上,可以避免编译器警告.但是依赖于你的方法的顺序是令人讨厌的.有没有办法绕过这个编译器警告,而不必按任何特定的顺序放置你的方法?

Jac*_*kin 7

不,没有.期间.

编译器解析代码自上而下的,所以请,只要把你的私人@interface确定指标上面@implementation,你会被所有的好去.

  • ....这个问题就是为什么首先创建了类扩展(这个以及能够将readonly属性提升为readwrite的能力).与类别不同,类扩展的方法**就像@interface中声明的方法一样.但是,正如雅各布回答的那样,扩展必须在@implementation编译之前可见! (4认同)