首页 > 代码库 > 【OC语法快览】五、设计类接口

【OC语法快览】五、设计类接口

Designing a Class Interface

      设计类接口


The Objective-C syntax for creating a class is very simple. It typically comes in two parts. 
创建类的语法是很简单的,通常包括两部分。

The class interface is usually stored in the ClassName.h file, and defines instance variables and public methods. 
类接口通常定义实例变量和公共方法(public),保存在“类名.h(ClassName.h )”文件中。

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. 
类接口的实现文件保存在“类名.m(ClassName.m)”文件中,包括公共方法的真正实现代码。也经常本文件中定义私有方法,私有方法不能被客户类调用。

Here‘s what an interface file looks like. The class is called Photo, so the file is named Photo.h:
下面是一个类接口文件实例,类名是Photo,所以文件名命名为Photo.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. 
首先,我们导入Cocoa.h文件,加入Cocoa应用需要的所有基础类。指令#import 保证只加入一次,即使多次使用。

The @interface says that this is a declaration of the class Photo. The colon specifies the superclass, which is NSObject. 
 @interface 表明这是一个Photo类声明。冒号(:)指定其父类为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. 
在大括号里面,定义了两个实例变量:caption 和 photographer 。他们都是NSStrings字符串,也可以使任意对象类型,包括id类型。

Finally, the @end symbol ends the class declaration.
最后, @end 标识结束类声明。
 

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. 
切记,OC方法通常省略掉"get" 前缀。方法前的中划线标识这是一个实例对象方法,加号则标识为类方法。

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:
编译器默认方法的返回值是一个id对象,所有的输入值也是id。上面的代码技术上是正确的,却不实用。下面的代码给方法具体化了返回值类型:

 
#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.
设值方法没有返回值,所以为void类型。




原文:learn_objective_C part 5