Objective-C 裡的初始化方法其實就是一般的 instance method,只是慣例上以 init 開頭。預設的 init 不接受參數,實際開發時為了方便建立帶初始狀態的物件,往往會自己設計參數化的初始化器。以下用一個 Iphone 類別示範兩者的差異。
#import <Foundation/Foundation.h>
#import "Iphone.h"
int main(int argc, const char * argv[]) {
// Iphone *phone1 = [Iphone new];
// phone1->_cpu = 1.5;
// phone1->_ram = 512;
// alloc 配置記憶體,init 初始化成員,兩步可合併撰寫
Iphone *phone = [[Iphone alloc] init];
phone->_ram = 512;
NSLog(@"%@", phone);
// 自定義初始化器一:指定螢幕尺寸
Iphone *phone2 = [[Iphone alloc] initWithIphoneSize:IphoneSize4point0];
NSLog(@"%@", phone2);
// 自定義初始化器二:尺寸與顏色
Iphone *phone3 = [[Iphone alloc] initWithIphoneSize:IphoneSize4point0
andPhoneColor:IphoneColorBlack];
return 0;
}
#import <Foundation/Foundation.h>
enum IphoneSize {
IphoneSize3point5, // 3.5 吋
IphoneSize4point0, // 4.0 吋
IphoneSize4point7, // 4.7 吋
IphoneSize5point5 // 5.5 吋
};
typedef enum IphoneSize IphoneSize;
enum IphoneColor { IphoneColorWhite, IphoneColorBlack };
typedef enum IphoneColor IphoneColor;
enum IphoneFlashLightStatus {
IphoneFlashLightStatusOpen,
IphoneFlashLightStatusClose,
IphoneFlashLightStatusAuto
};
typedef enum IphoneFlashLightStatus IphoneFlashLightStatus;
@interface Iphone : NSObject {
@public
IphoneSize _size; // 螢幕尺寸
IphoneColor _color; // 顏色
float _cpu; // CPU 規格
float _ram; // 內部容量
}
-(void)openFlashLight;
-(void)closeFlashLight;
-(void)flaseLightAuto;
-(void)cameraWithFlashLightStatus:(IphoneFlashLightStatus)flaseLightStatus;
-(NSString *)getColorWithIphoneColor:(IphoneColor)iphoneColor;
+(NSString *)getColorWithIphoneColor:(IphoneColor)iphoneColor;
// 自定義初始化器
-(Iphone *)initWithIphoneSize:(IphoneSize)iphoneSize;
-(Iphone *)initWithIphoneSize:(IphoneSize)iphoneSize andPhoneColor:(IphoneColor)iphoneColor;
@end
自定義初始化器有兩個慣例:一是必須是物件方法(前導減號),二是名稱一律以 init 開頭。實作時記得先呼叫 self = [super init] 並檢查回傳值不為 nil,再設定各項成員,最後回傳 self。
另外,Objective-C 的多個初始化器之間常用 designated initializer(指定初始化器)的關係串接:參數最少的呼叫參數最多的,避免初始化邏輯散落在各處。上面範例中的 initWithIphoneSize: 就可以 internally 呼叫 initWithIphoneSize:andPhoneColor: 並帶入預設顏色。