15. 用前綴避免命名空間衝突
16. 提供全能化初始方法
17. 實現 description 方法
18. 盡量使用不可變對象
Objective-C 沒有其他語言那種內建的命名空間機制,因此起名時必須主動避開潛在衝突,否則很容易撞名。
唯一的解法是變相實作命名空間:為所有名稱加上合適的前綴。前綴可以取自公司名、應用程式名,或兩者的組合。假設你的公司叫 Effective Widgets,那麼跨專案共用的那部分程式可以用 EWS;只用在名為 Effective Browser 的瀏覽器專案裡的程式,則用 EWB。
用 Cocoa 開發時要特別注意:Apple 保留使用所有雙字母前綴的權利,所以自己選的前綴應該是三個字母,以免與框架內的類名相撞。
而且不只是類名——應用程式中的所有名稱都該加前綴,包括 category。另外還有一個容易引發衝突的地方:實作檔裡所有的純 C 函式與全域變數。
// EOCSoundPlayer.m
#import "EOCSoundPlayer.h"
#import <AudioToolbox/AudioToolbox.h>
void completion(SystemSoundID ssID, void *clientData) {
// code
}
@implementation EOCSoundPlayer
// code
@end
這段程式看起來完全正常,但在該目標檔案的符號表中會看到一個名為 _completion 的符號。雖然這個函式定義在實作檔而非標頭檔,它仍然是頂層符號。若別處又定義了一個 completion 函式,就會發生重複符號錯誤。所以這類 C 函式的名稱也該加前綴,例如 EOCSoundPlayerCompletion。
同理,若你把第三方庫的原始碼直接編進自己的專案,應該為那份程式碼也加上自己的前綴,避免與其他庫互撞。
所有物件都要初始化。有些物件不需要開發者提供額外資訊,這種「能為物件提供完成工作所需必要資訊」的初始化方法,就叫做全能初始化方法(designated initializer)。
即使一個類別有多種建立方式,仍應在其中指定一個全能初始化方法,並讓其他初始化方法都來呼叫它。NSDate 就是範例:
- (id)init; - (id)initWithTimeIntervalSinceNow:(NSTimeInterval)secs; - (id)initWithTimeInterval:(NSTimeInterval)secsToBeAdded sinceDate:(NSDate *)date; - (id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)ti; - (id)initWithTimeIntervalSince1970:(NSTimeInterval)secs;
其中 initWithTimeIntervalSinceReferenceDate: 是全能初始化方法,其餘都要呼叫它。於是只有在全能初始化方法裡才會真正儲存內部資料。
// EOCRectangle.h
#import <Foundation/Foundation.h>
@interface EOCRectangle : NSObject
@property (nonatomic, assign, readonly) float width;
@property (nonatomic, assign, readonly) float height;
// 全能初始化方法
- (id)initWithWidth:(float)width andHeight:(float)height;
@end
// EOCRectangle.m
#import "EOCRectangle.h"
@implementation EOCRectangle
- (id)initWithWidth:(float)width andHeight:(float)height {
if ((self = [super init])) {
_width = width;
_height = height;
}
return self;
}
@end
問題來了:如果用 [[EOCRectangle alloc] init] 建立物件,呼叫的是 NSObject 的 init,全部實例變數都會是 0。這時要嘛給預設值,要嘛直接拋出異常:
// 方式一:給預設值並轉呼全能初始化方法
- (id)init {
return [self initWithWidth:5.0 andHeight:10.0];
}
// 方式二:直接拋出異常,強制呼叫者改用正確方法
- (id)init {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Must use initWithWidth:andHeight: instead."
userInfo:nil];
}
再建一個 EOCSquare,作為 EOCRectangle 的子類,專門表示正方形(寬與高必須相等)。這裡的原則是:全能初始化方法的呼叫鏈必須維繫。如果超類的初始化方法不適用於子類,就應該重寫它。
// EOCSquare.h
#import "EOCRectangle.h"
@interface EOCSquare : EOCRectangle
// 子類的全能初始化方法
- (id)initWithDimension:(float)dimension;
@end
// EOCSquare.m
#import "EOCSquare.h"
@implementation EOCSquare
- (id)initWithDimension:(float)dimension {
return [super initWithWidth:dimension andHeight:dimension];
}
// 子類的全能初始化方法與超類不同時,要重寫超類的全能初始化方法
- (id)initWithWidth:(float)width andHeight:(float)height {
float dimension = MAX(width, height);
return [self initWithDimension:dimension];
}
@end
如此一來就不必在子類重寫 init 了。呼叫 [[EOCSquare alloc] init] 時,會走超類已重寫的 init,它會拋出異常或轉呼 initWithWidth:andHeight:;由於子類已重寫該方法,實際執行的是子類版本,而它又會轉呼子類自己的全能初始化方法。整條鏈完整無缺口。
除錯時經常需要印出物件資訊。麻煩一點的做法是逐個屬性 printf,但更常見的是直接:
NSArray *object = @[@"A string", @(123)]; NSLog(@"object = %@", object);
輸出:
object = (
"A string",
123
)
如果對自訂類別這樣做,輸出會是:
object = <EOCPerson: 0x7fd9a1600600>
這種資訊幾乎沒有幫助。若沒有重寫 description,就會用到 NSObject 的預設實作——它定義在 NSObject 協議中,只印出類名與記憶體位址。想輸出更有用的內容,就得自己重寫:
#import <Foundation/Foundation.h>
@interface EOCPerson : NSObject
@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
@end
@implementation EOCPerson
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
if ((self = [super init])) {
_firstName = [firstName copy];
_lastName = [lastName copy];
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, \"%@ %@\">",
[self class], self, _firstName, _lastName];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
EOCPerson *person = [[EOCPerson alloc] initWithFirstName:@"Bob" lastName:@"Smith"];
NSLog(@"person = %@", person);
}
return 0;
}
輸出:
person = <EOCPerson: 0x7fd9a1600600, "Bob Smith">
也可以改用字典格式,讓屬性結構更清楚:
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, %@>",
[self class], self,
@{@"firstName": _firstName, @"lastName": _lastName}];
}
輸出:
person = <EOCPerson: 0x7fd9a1600600, {
firstName = Bob;
lastName = Smith;
}>
NSObject 協議中還有一個與 description 極為相似的方法:debugDescription。它只在開發者在除錯器中以控制台命令印出物件時才會被呼叫。NSObject 的預設實作是直接轉呼 description。
因此一個實務上的好習慣是:description 只描述普通資訊,debugDescription 放更詳盡的內容(例如全部屬性、內部狀態、關聯物件)。
- (NSString *)description {
return [NSString stringWithFormat:@"%@ %@", _firstName, _lastName];
}
- (NSString *)debugDescription {
return [NSString stringWithFormat:@"<%@: %p, \"%@ %@\">",
[self class], self, _firstName, _lastName];
}
在程式中插入中斷點:
int main(int argc, const char * argv[]) {
@autoreleasepool {
EOCPerson *person = [[EOCPerson alloc] initWithFirstName:@"Bob" lastName:@"Smith"];
NSLog(@"person = %@", person);
// 在本行插入中斷點
}
return 0;
}
程式停在斷點時,於除錯控制台輸入 po person(LLDB 的 print-object 指令),會看到:
(lldb) po person <EOCPerson: 0x7fd9a1600600, "Bob Smith">
注意這裡印出的是 debugDescription 的結果,而非 NSLog 用到的 description。
屬性預設是 readwrite,這樣設計出來的類別都是可變的。但實際建模時,很多資料並不需要被改變。
有時你想在物件內部修改被封裝的資料,卻不希望外部能改。標準做法是在 class-continuation(類別延伸)中,把 readonly 屬性重新宣告為 readwrite。此外,物件內表示各種容器的屬性也可以設為不可變,改由提供方法讓使用者操作。
// EOCPerson.h
#import <Foundation/Foundation.h>
@interface EOCPerson : NSObject
// 對外一律只讀
@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
@property (nonatomic, strong, readonly) NSSet *friends;
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
// 提供方法讓呼叫方操作 friends
- (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 *_internalFriends;
}
// 對外回傳不可變副本
- (NSSet *)friends {
return [_internalFriends copy];
}
- (void)addFriend:(EOCPerson *)person {
[_internalFriends addObject:person];
}
- (void)removeFriend:(EOCPerson *)person {
[_internalFriends removeObject:person];
}
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
if ((self = [super init])) {
_firstName = [firstName copy];
_lastName = [lastName copy];
_internalFriends = [NSMutableSet new];
}
return self;
}
@end
如果直接用 NSMutableSet 實作 friends 屬性,呼叫方可以不經過 addFriend: 與 removeFriend: 就直接操作它。這樣做很危險——等於從底層竄改了物件內部用來存放朋友的那個集合,而 EOCPerson 完全不知情,可能導致物件內各資料不一致。
另外要理解一件事:用延伸把 readonly 改成 readwrite,並不是絕對的安全防護。外部仍然可以透過 KVC 修改:
[person setValue:@"Seven" forKey:@"firstName"];
甚至可以繞過 setter,用 runtime 的型別資訊查詢該屬性對應的實例變數在記憶體配置中的位移,直接寫入。
不過這兩種做法都屬於違反規範的操作,不該因為存在這些漏洞,就放棄「盡量讓物件不可變」這個好習慣。不可變設計的目的不是防止惡意竄改,而是從 API 層面清楚表達意圖:這些資料由物件自己維護,呼叫方請不要插手。這能大幅減少多人在同一份程式碼上協作時的誤用。