我想知道 Objective-C 中的 @interface 是什么?它只是程序员想要声明变量、类名或方法名的地方吗?我不确定它是否像 Java 中的接口。
还有关于 Objective-C 中的 @protocol。它似乎更像 Java 中的接口。
请问有人能给我详细的解释吗?非常感谢。
我想知道 Objective-C 中的 @interface 是什么?它只是程序员想要声明变量、类名或方法名的地方吗?我不确定它是否像 Java 中的接口。
还有关于 Objective-C 中的 @protocol。它似乎更像 Java 中的接口。
请问有人能给我详细的解释吗?非常感谢。
接口是用于定义类属性和操作的地方。你必须也要设置实现。
协议就像Java中的接口。
例如:
@protocol Printing
-(void) print;
@end
可以通过在接口中(令人困惑地)声明来实现
@interface Fraction: NSObject <Printing, NSCopying> {
//etc..
对于Java开发者来说,令人困惑的是花括号{}
不是接口的结尾,例如:
@interface Forwarder : Object
{
id recipient;
} //This is not the end of the interface - just the operations
- (id) recipient;
- (id) setRecipient:(id) _recipient;
//these are attributes.
@end
//This is the end of the interface
如果您查看这个,应该会很有帮助。我认为它非常有助于理解。
从文章中:
@interface
#ifndef __FOO_H__
#define __FOO_H__
class Foo
{
...
};
#include "Foo.h"
...
@interface Foo : NSObject
{
...
}
@end
#import "Foo.h"
@implementation Foo
...
@end
@protocol
struct MyInterface
{
void foo() = 0;
}
class A : MyInterface
{
public:
void override foo() { ... }
}
@protocol MyInterface
-(void) foo;
@end
@interface Foo : NSObject <MyInterface>
{
-(void) foo {...}
...
}
@end
@protocol
定义了一些通用方法,@interface
定义了一些自定义方法,而 @implementation
则实现了该接口。@interface
没有任何实现。此外,如果 foo
方法与协议中的方法相同,则不应在接口中重复定义。 - S.M.Mousavi@interface
在Objective-C中与Java接口无关。它仅声明一个类的公共接口,即其公共API。(以及成员变量,正如您已经观察到的那样。) Java风格的接口在Objective-C中被称为协议,并使用@protocol
指令声明。建议阅读由苹果公司编写的《Objective-C编程语言》,这是一本很好的书籍-简短且非常易懂。
myObject.lpVtbl->x(&myObject)
),而是通过双重接口接收消息,类似于CmyObject.lpVtbl->Invoke(&myObject, "x", &argArray);
。因此,协议和接口似乎用于向编译器提供信息以生成运行时和编译时类型检查。因此,除非您将脚本引擎/COM引入项目中,否则在C ++中没有真正的并行。 - Dmytro