@interface and @protocol explanation?

Objective C

Objective C Problem Overview


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.

Objective C Solutions


Solution 1 - Objective C

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.

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.

@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

Solution 2 - Objective C

probably good if you take a look at this + I thought it was great help to understand

From the article:

@interface

C++

Foo.h

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

Foo.cpp

#include "Foo.h"
...

Objective-C

Foo.h

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

Foo.m

#import "Foo.h"

@implementation Foo
...
@end

@protocol

C++

struct MyInterface
{
  void foo() = 0;
}

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

Objective-C

@protocol MyInterface
-(void) foo;
@end

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

Solution 3 - Objective C

The @interface in 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 @protocol directive. You should read The Objective-C Programming Language by Apple, it’s a good book – short and very accessible.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRockerView Question on Stackoverflow
Solution 1 - Objective CJohnno NolanView Answer on Stackoverflow
Solution 2 - Objective CAndersKView Answer on Stackoverflow
Solution 3 - Objective CzoulView Answer on Stackoverflow