【发布时间】:2009-11-05 08:38:34
【问题描述】:
我想知道目标 C 中的@interface 是什么?它只是程序员想要声明变量、类名或方法名的地方吗……?我不确定它是否像 Java 中的接口。 还有关于目标 C 中的@protocol。看起来更像是Java中的接口。 谁能给我详细的解释。我真的很感激。
【问题讨论】:
标签: objective-c
我想知道目标 C 中的@interface 是什么?它只是程序员想要声明变量、类名或方法名的地方吗……?我不确定它是否像 Java 中的接口。 还有关于目标 C 中的@protocol。看起来更像是Java中的接口。 谁能给我详细的解释。我真的很感激。
【问题讨论】:
标签: objective-c
接口是定义类的属性和操作的地方。你也必须制定实施。
协议就像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)),而是通过类似于 c myObject.lpVtbl->Invoke(&myObject, "x", &argArray); 的双接口接收消息。因此,协议和接口似乎可以为编译器提供信息以生成运行时和编译时类型检查。因此,除非您在项目中引入脚本引擎/COM,否则 C++ 中没有真正的并行。
如果你看看 this 可能会很好 + 我认为这对理解很有帮助
来自文章:
@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的方法和protocol的方法一样,就不应该在接口上重复。
Objective-C 中的@interface 与Java 接口无关。它只是声明了一个类的公共接口,即它的公共 API。 (以及成员变量,正如您已经观察到的那样。)Java 风格的接口在 Objective-C 中称为协议,并使用 @protocol 指令声明。您应该阅读 Apple 的 The Objective-C Programming Language,这是一本好书——简短且易于理解。
【讨论】: