API 設計的品質,往往決定一個程式庫能否被長期維護。本條目整理四項要點:
類、方法與變數的命名,是 Objective-C 程式設計的重要一環。它的語法結構讓程式碼讀起來近乎自然語句,名稱中經常出現 in、for、with 這類其他語言眼中的「多餘字眼」:
// C++
string text = "The quick brown fox jumped over the lazy dog";
string newText = text.replace("fox", "cat");
// Objective-C
NSString *text = @"The quick brown fox jumped over the lazy dog";
NSString *newText = [text stringByReplacingOccurrencesOfString:@"fox"
withString:@"cat"];
text.replace("fox", "cat") 單看字面,無從判斷究竟是把 fox 換成 cat,還是反之;Objective-C 的寫法雖然長一些,語意卻毫無歧義。
C++ 與 Java 習慣簡短的方法名,想知道每個參數的用途就得翻原型宣告,可讀性因此打折。以矩形類為例:
// C++
class Rectangle {
public:
Rectangle(float width, float height);
float getWidth();
float getHeight();
private:
float width;
float height;
};
// Objective-C
@interface EOCRectangle : NSObject
@property (nonatomic, assign, readonly) float width;
@property (nonatomic, assign, readonly) float height;
- (id)initWithWidth:(float)width andHeight:(float)height;
@end
建立實例時差異更明顯:
// C++
Rectangle aRectangle = new Rectangle(5.0f, 10.0f);
// Objective-C
EOCRectangle *aRectangle = [[EOCRectangle alloc] initWithWidth:5.0f andHeight:10.0f];
C++ 那行程式碼裡,5.0f 與 10.0f 分別代表什麼完全看不出來;即便猜到是尺寸,也不知道寬度在前還是高度在前,只能回去查定義。Objective-C 的寫法則自帶說明。
不過長名稱雖有助閱讀,也不能长到失控,仍應力求精準:
// 好的方法名
- (EOCRectangle *)unionRectangle:(EOCRectangle *)rectangle;
- (float)area;
// 不好的方法名
- (EOCRectangle *)union:(EOCRectangle *)rectangle; // 不夠清晰
- (float)calculateTheArea; // 過於冗長
命名時的注意事項可歸納為:
str 這類縮寫,應寫成 string 這樣的完整拼法。has 或 is 前綴。get 這個前綴保留給那些透過輸出參數帶回結果的方法。Objective-C 沒有辦法把方法標記為私有——任何物件都能回應任何訊息。因此「私有」這件事只能依靠命名慣例來表達。慣用的做法是加上 p_ 前綴,p 代表 private,底線則把這個標記與真正的方法名區隔開。
#import <Foundation/Foundation.h>
@interface EOCObject : NSObject
- (void)publicMethod;
@end
@implementation EOCObject
// 公有方法
- (void)publicMethod {
// code
}
// 私有方法
- (void)p_privateMethod {
// code
}
@end
蘋果自己喜歡用單一底線作私有方法前綴,因此請不要照抄這個做法,否則極可能無意間覆寫父類中的同名方法。
#import <UIKit/UIKit.h>
@interface EOCViewController : UIViewController
@end
@implementation EOCViewController
- (void)_resetViewController {
// code
}
@end
這段程式碼看起來沒問題,但 UIViewController 本身已經實作了一個叫 _resetViewController 的方法。這樣寫,所有呼叫都會轉而執行子類的版本;而由於父類中的同名方法並未對外公開,除非深入研究 UIKit,否則根本不可能察覺自己覆寫了它。
許多語言都有例外(exception)機制,Objective-C 也不例外,但有一點必須牢記:ARC 在預設情況下並不是例外安全的。也就是說,一旦拋出例外,原本應在作用域結束時釋放的物件將不會被自動釋放。若要產出例外安全的程式碼,需要開啟編譯器旗標 -fobjc-arc-exceptions。
Objective-C 目前採用的策略是:只在極罕見的情況下拋出例外,且例外一旦拋出便不考慮恢復,應用直接終止。例外只用來處理嚴重錯誤;一般錯誤則讓方法回傳 nil/0,或改用 NSError。
例如初始化無法依傳入參數完成時,就讓它回傳 nil:
- (id)initWithValue:(id)value {
if ((self = [super init])) {
if (/* 無法以 value 初始化實例 */) {
self = nil;
} else {
// 初始化
}
}
return self;
}
NSError 的用法更靈活,可以把失敗原因回報給呼叫方。NSError 物件封裝了三項資訊:錯誤域(error domain,字串)、錯誤碼(error code,整數)、使用者資訊(user info,字典)。
// EOCErrors.h
#import <Foundation/Foundation.h>
// 宣告全域變數:錯誤域
extern NSString *const EOCErrorDomain;
// 錯誤碼
typedef NS_ENUM(NSUInteger, EOCError) {
EOCErrorUnknown = -1,
EOCErrorInternalInconsistency = 100,
EOCErrorGeneralFault = 105,
EOCErrorBadInput = 500,
};
@interface EOCErrors : NSObject
- (BOOL)doSomething:(NSError **)error;
@end
// EOCErrors.m
#import "EOCErrors.h"
NSString *const EOCErrorDomain = @"EOCErrorDomain";
@implementation EOCErrors
- (BOOL)doSomething:(NSError *__autoreleasing *)error {
if (/* 發生錯誤 */) {
if (error) {
*error = [NSError errorWithDomain:EOCErrorDomain
code:EOCErrorGeneralFault
userInfo:@{@"EOCErrorUserInfo": @"General fault occurs!"}];
}
return NO;
}
return YES;
}
@end
呼叫方即可透過輸出參數取回錯誤物件:
NSError *error = nil;
BOOL ret = [object doSomething:&error];
if (error) {
// 處理錯誤
}
使用物件時經常需要複製它。在 Objective-C 中,這由 copy 方法完成。若希望自己的類支援複製,就要實作 NSCopying 協議,而該協議只有一個方法:
- (id)copyWithZone:(NSZone *)zone;
如今每個程式只有一個區域(預設區域),所以實作時不必擔心 zone 參數。copy 方法由 NSObject 實作,它只是以預設區域為參數去呼叫 copyWithZone:。因此真正需要覆寫的是 copyWithZone:。
// EOCPerson.h
#import <Foundation/Foundation.h>
@interface EOCPerson : NSObject <NSCopying>
@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
- (void)addFriend:(EOCPerson *)person;
- (void)removeFriend:(EOCPerson *)person;
@end
// EOCPerson.m
#import "EOCPerson.h"
@interface EOCPerson ()
@property (nonatomic, copy, readwrite) NSString *firstName;
@property (nonatomic, copy, readwrite) NSString *lastName;
@end
@implementation EOCPerson {
NSMutableSet *_friends;
}
- (void)addFriend:(EOCPerson *)person {
[_friends addObject:person];
}
- (void)removeFriend:(EOCPerson *)person {
[_friends removeObject:person];
}
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
if ((self = [super init])) {
_firstName = [firstName copy];
_lastName = [lastName copy];
_friends = [NSMutableSet new];
}
return self;
}
// 實作 NSCopying 協議
- (id)copyWithZone:(NSZone *)zone {
// 以全能初始化方法建立複本
EOCPerson *copy = [[[self class] allocWithZone:zone] initWithFirstName:_firstName
lastName:_lastName];
// 將實例變數複製到複本
copy->_friends = [_friends mutableCopy];
return copy;
}
@end
範例中的 _friends 是以 mutableCopy 複製的,該方法來自另一個名為 NSMutableCopying 的協議,同樣只定義一個方法:
- (id)mutableCopyWithZone:(NSZone *)zone;
規則很直接:需要回傳不可變複本時實作 NSCopying,需要回傳可變複本時實作 NSMutableCopying。
[NSMutableArray copy] // 回傳 NSArray
[NSArray mutableCopy] // 回傳 NSMutableArray
撰寫複製方法時還要決定另一件事:執行深複製還是淺複製。深複製在複製物件自身的同時,會把底層資料一併複製;淺複製則只複製容器本身,不複製其中元素。Foundation 框架中的所有容器預設都執行淺複製。
以 EOCPerson 為例,若需要深複製,可以另外提供一個專用方法:
- (id)deepCopy {
EOCPerson *copy = [[[self class] alloc] initWithFirstName:_firstName lastName:_lastName];
// copyItems 參數設為 YES,會向容器中每個元素發送 copy 訊息,
// 以複製好的元素建立新集合回傳
copy->_friends = [[NSMutableSet alloc] initWithSet:_friends copyItems:YES];
return copy;
}