objective-c @interface 和@protocol 解释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1679145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@interface and @protocol explanation?
提问by Rocker
I would like to know what the @interface in objective C is? is it just where the programmer want to declare the variables, class name or method names...? I am not sure whether it is like interface in Java. And about the @protocol in objective C as well. It seems like the interface in Java more. Could anyone give me detail explanation please. I truly appreciate it.
我想知道目标 C 中的 @interface 是什么?它只是程序员想要声明变量、类名或方法名的地方吗……?我不确定它是否像 Java 中的接口。还有关于目标 C 中的@protocol。似乎Java中的接口更多。谁能给我详细的解释请。我真的很感激。
回答by Johnno Nolan
An interface is where you define the attributes and operations of class. You must set out the implementation too.
接口是您定义类的属性和操作的地方。您也必须制定实施。
A protocol is like an interface for java.
协议就像 java 的接口。
e.g.
例如
@protocol Printing
-(void) print;
@end
can be implemented
可以实施
by declaring (confusingly in the interface)
通过声明(在界面中令人困惑)
@interface Fraction: NSObject <Printing, NSCopying> {
//etc..
The confusing thing for java developers is that the curly braces {}are not the end of the interface e.g.
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
回答by AndersK
probably good if you take a look at this+ I thought it was great help to understand
如果你看看这个可能很好+我认为这对理解有很大帮助
From the article:
从文章:
@interface
@界面
C++
C++
Foo.h
foo.h
#ifndef __FOO_H__
#define __FOO_H__
class Foo
{
...
};
Foo.cpp
文件
#include "Foo.h"
...
Objective-C
目标-C
Foo.h
foo.h
@interface Foo : NSObject
{
...
}
@end
Foo.m
foo.m
#import "Foo.h"
@implementation Foo
...
@end
@protocol
@协议
C++
C++
struct MyInterface
{
void foo() = 0;
}
class A : MyInterface
{
public:
void override foo() { ... }
}
Objective-C
目标-C
@protocol MyInterface
-(void) foo;
@end
@interface Foo : NSObject <MyInterface>
{
-(void) foo {...}
...
}
@end
回答by zoul
The @interfacein Objective-C has nothing to do with Java interfaces. It simply declares a?public interface of a class, its public API. (And member variables, as you have already observed.) Java-style interfaces are called protocols in Objective-C and are declared using the @protocoldirective. You should read The Objective-C Programming Languageby Apple, it's a good book – short and very accessible.
将@interface在Objective-C无关的Java接口。它只是声明了一个类的公共接口,即它的公共 API。(还有成员变量,正如您已经观察到的。)Java 风格的接口在 Objective-C 中称为协议,并使用@protocol指令进行声明。您应该阅读Apple 的The Objective-C Programming Language,这是一本好书 - 简短易懂。

