我想知道目标C中的@interface是什么?程序员只是想在其中声明变量,类名还是方法名...?我不确定它是否类似于Java中的接口。还有目标C中的@protocol。似乎Java中的接口更多。谁能给我详细解释。我真的很感激。
Answers:
接口是定义类的属性和操作的地方。您还必须列出实现。
协议就像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
myObject.lpVtbl->x(&myObject))那样通过.x或.y接收消息,而是通过类似于c的双重接口接收消息myObject.lpVtbl->Invoke(&myObject, "x", &argArray);。因此,协议和接口似乎可以为编译器提供生成运行时和编译时间类型检查的信息。因此,除非在项目中引入脚本引擎/ COM,否则C ++中没有真正的并行处理。
如果您看一下这可能很好,+我认为这对理解很有帮助
从文章:
@接口
#ifndef __FOO_H__
#define __FOO_H__
class Foo
{
...
};
#include "Foo.h"
...
@interface Foo : NSObject
{
...
}
@end
#import "Foo.h"
@implementation Foo
...
@end
@协议
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方法与协议的方法相同,则不应在接口上重复该方法。
将@interface在Objective-C无关的Java接口。它只是声明一个类的公共接口,即其公共API。(和成员变量一样,您已经观察到了。)Java风格的接口在Objective-C中称为协议,并使用@protocol指令进行声明。您应该阅读Apple的《 Objective-C编程语言》,这是一本好书–简短易懂。