为什么允许我在没有在Objective-C的头文件中声明的实现中编写和使用方法?

时间:2021-12-26 19:57:04
@interface SomeClass : NSObject
{
}
@end

@implementation SomeClass
-(void) awesomeMethod600
{
}
@end

No error, and awesomeMethod600 works.

没有错误,也没有错误。

2 个解决方案

#1


7  

The method declarations in the class interfaces are there for the compiler (to suppress warnings), since method lookup in Objective-C is done at runtime, and not compile time.

由于Objective-C中的方法查找是在运行时完成的,而不是在编译时完成的,所以类接口中的方法声明是为编译器提供的(以避免警告)。

#2


0  

Perspx is right.

Perspx是正确的。

Try building this in XCode:

尝试在XCode中构建这个:

@implementation SomeClass
-(void)awesomeMethod {
    [self notAwesomeMethod];
}    

-(void)notAwesomeMethod {}
@end

You should see a warning that says 'SomeClass' may not respond to '-notAwesomeMethod'. Try inverting the order of the method definitions... no error since notAwesomeMethod is now already defined, and thus the compiler knows about it. Class interfaces do this upfront.

你应该看到一个警告,上面写着“SomeClass”可能不会回应“-notAwesomeMethod”。尝试颠倒方法定义的顺序…没有错误,因为notawesomethod现在已经定义,因此编译器知道它。类接口在前面做这个。

This is also nice behavior because you can choose to only publicize the class's public interface, and keep any internal private methods out of the .h file.

这也是一种很好的行为,因为您可以选择只公开类的公共接口,并在.h文件之外保留任何内部私有方法。

#1


7  

The method declarations in the class interfaces are there for the compiler (to suppress warnings), since method lookup in Objective-C is done at runtime, and not compile time.

由于Objective-C中的方法查找是在运行时完成的,而不是在编译时完成的,所以类接口中的方法声明是为编译器提供的(以避免警告)。

#2


0  

Perspx is right.

Perspx是正确的。

Try building this in XCode:

尝试在XCode中构建这个:

@implementation SomeClass
-(void)awesomeMethod {
    [self notAwesomeMethod];
}    

-(void)notAwesomeMethod {}
@end

You should see a warning that says 'SomeClass' may not respond to '-notAwesomeMethod'. Try inverting the order of the method definitions... no error since notAwesomeMethod is now already defined, and thus the compiler knows about it. Class interfaces do this upfront.

你应该看到一个警告,上面写着“SomeClass”可能不会回应“-notAwesomeMethod”。尝试颠倒方法定义的顺序…没有错误,因为notawesomethod现在已经定义,因此编译器知道它。类接口在前面做这个。

This is also nice behavior because you can choose to only publicize the class's public interface, and keep any internal private methods out of the .h file.

这也是一种很好的行为,因为您可以选择只公开类的公共接口,并在.h文件之外保留任何内部私有方法。