Interface and Implementation
As you already know from Chapter 2, all your code is going to go into some class or other. So the first thing we must do is specify what is meant by putting code “into a class” in Objective-C. How does Objective-C say, linguistically and structurally, “This is the code for such-and-such a class”?
To write the code for a class, you must provide two chunks or sections of code, called the interface and the implementation. Here’s the complete minimum code required to define a class called MyClass. This class is so minimal that it doesn’t even have any methods of its own:
@interface MyClass @end @implementation MyClass @end
The @interface and @implementation compiler directives show the compiler where the interface and implementation sections begin for the class that’s being defined, MyClass; the corresponding @end lines show where each of those sections end.
In real life, the implementation section is where any methods for MyClass would be defined. So here’s a class that’s actually defined to do something:
@interface MyClass
@end
@implementation MyClass
- (NSString*) sayGoodnightGracie {
return @"Good night, Gracie!";
}
@endObserve how a method is defined. The first line is just like a method declaration, stating the type of method (class or instance), the type of value returned, and the name of the method along with the types of any parameters and local names for those parameters (see Chapter 3). That’s followed by curly braces containing the code to be executed ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access