May 27, 2014

Fast food objective-c (part 5) : Designing a Class Interface

Designing a Class Interface

learnobjectivec-editorwindowinset
The Objective-C syntax for creating a class is very simple. It typically comes in two parts. 
The class interface is usually stored in theClassName.h file, and defines instance variables and public methods. 
The implementation is in the ClassName.m file and contains the actual code for these methods. It also often defines private methods that aren't available to clients of the class. 
Here's what an interface file looks like. The class is called Photo, so the file is namedPhoto.h:
 
#import <Cocoa/Cocoa.h>
@interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}

@end 
First, we import Cocoa.h, to pull in all of the basic classes for a Cocoa app. The#import directive automatically guards against including a single file multiple times. 
The @interface says that this is a declaration of the class Photo. The colon specifies the superclass, which is NSObject
Inside the curly brackets, there are two instance variables: caption and photographer. Both are NSStrings, but they could be any object type, including id. 
Finally, the @end symbol ends the class declaration.

Add Methods

Let's add some getters for the instance variables:
#import <Cocoa/Cocoa.h>
@interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}
caption;
-
photographer;
@end

Remember, Objective-C methods typically leave out the "get" prefix. A single dash before a method name means it's a instance method. A plus before a method name means it's a class method. 
By default, the compiler assumes a method returns an id object, and that all input values are id. The above code is technically correct, but it's unusual. Let's add specific types for the return values:
#import <Cocoa/Cocoa.h>
@interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}
- (NSString*) caption;
- (
NSString*) photographer;
@end
Now let's add setters:
#import <Cocoa/Cocoa.h>
@interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}
- (NSString*) caption;
- (NSString*) photographer;
- (void) setCaption: (NSString*)input;
- (void)
setPhotographer: (NSString*)input;
@end
Setters don't need to return a value, so we just specify them as void.​

No comments:

Post a Comment