Header/Interface Files
Creating a class creates two different files: an interface (or header) file (.h) and an implementation file (.m). The interface file is used to define a list of all of the methods and properties that your class will be using. The implementation file, on the other hand, is where you’ll go to write the code that makes everything defined in the header file work.
The #import
directive: Directives are commands that are added to your files that help Xcode and its associated tools build your application.
The @interface
directive and Instance variables: Line 3 uses the @interface
directive to begin a set of lines (enclosed in {}
braces) to describe all the instance variables that your class will be providing.
What’s a Protocol: Protocols are a unique feature of Objective-C that sound complicated but really aren’t. Sometimes, you will come across features that require you to write methods to support their use—such as providing a list of items to be displayed in a table. The methods that you need to write are grouped together under a common name—this is known as a “protocol.”
Defining Methods: Lines 8 and 10 declare two methods that need to be implemented in the class:
The @property
directive: The @property
directive is used in conjunction with another command called syn- thesize in the implementation file to simplify how you interact with the instance variables that you’ve defined in your interface.
Ending the Interface File: To end the interface file, add @end
on its own line. This can be seen on line 14 of our example file:
Implementation Files
After you’ve defined your instance variables (or properties!) and methods in your interface file, you need to do the work of writing code to implement the logic of your application. The implementation file (.m) holds all of the “stuff” that makes your class work.
The #import
directive: The #import
directive kicks things off in line 1 by importing the interface file associated with the class:
The @implementation
directive: The implementation
directive, shown in line 3, tells Xcode what class the file is going to be implementing.
The @synthesize
directive: In line 5, we use the @synthesize
directive to, behind the scenes, generate the code for the getters and setters of an instance variable:
Method Implementation: The implementation file must restate the method definitions, but, rather than ending them with a semicolon (;), a set of curly braces, {}, is added at the end, as shown in lines 7–9 and 11–13. All the magic of your programming will take place between these braces: