@ interface 和@protocol 解释?

我想知道目标 C 中的@接口是什么?程序员只是想在这里声明变量、类名或方法名吗?我不确定它是否像 Java 中的接口。 关于目标 C 中的@协议,它看起来更像 Java 中的接口。 有人能给我详细解释一下吗? 我真的很感激。

64913 次浏览

接口是定义类的属性和操作的地方,还必须设置实现。

协议就像 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

C + +

#ifndef __FOO_H__
#define __FOO_H__
class Foo
{
...
};

Foo.cpp

#include "Foo.h"
...

目标 C

@interface Foo : NSObject
{
...
}
@end

阿福

#import "Foo.h"


@implementation Foo
...
@end

@ 草案

C + +

struct MyInterface
{
void foo() = 0;
}


class A : MyInterface
{
public:
void override foo() { ... }
}

目标 C

@protocol MyInterface
-(void) foo;
@end


@interface Foo : NSObject <MyInterface>
{
-(void) foo {...}
...
}
@end

Objective-C 中的 @interface与 Java 接口没有任何关系。它只是声明一个类的公共接口,即它的公共 API。(以及成员变量,正如您已经观察到的那样。)Java 样式的接口在 Objective-C 中称为协议,并使用 @protocol指令声明。你应该读读苹果公司的 Objective-C 程序设计语言,这是一本好书-简短,非常容易理解。