Apple 在 Cocoa Core Competencies 系列文件中,把「物件如何誕生」拆成了兩個步驟。這段說明看似基本,卻是 Objective-C 記憶體管理與面試題的根基。
An object comes into runtime existence through a two-step process that allocates memory for the object and sets its state to reasonable initial values. To allocate an Objective-C object, send an alloc or allocWithZone: message to the object's class. The runtime allocates memory for the object and returns a "raw" (uninitialized) instance of the class. It also sets a pointer (known as the isa pointer) to the object's class, zeros out all instance variables to appropriately typed values, and sets the object's retain count to 1.
After you allocate an object, you must initialize it. Initialization sets the instance variables of an object to reasonable initial values. It can also allocate and prepare other global resources needed by the object. You initialize an object by invoking an init method or some other method whose name begins with init. These initializer methods often have one or more parameters that enable you to specify beginning values of an object's instance variables. If these methods succeed in initializing an object, they return it; otherwise, they return nil. If an object's class does not implement an initializer, the Objective-C runtime invokes the initializer of the nearest ancestor instead.
建立物件需要兩個步驟:配置記憶體,然後初始化。
步驟一:配置記憶體。對類別送出 alloc 或 allocWithZone: 訊息,也就是常見的 [Class alloc],或較少見的 [Class allocWithZone:]。此時 runtime 會做四件事:配置記憶體、設定 isa 指標指向該物件的類別、把所有 instance variable 歸零成對應型別的合理值、並把 retain count 設為 1。這時候拿到的還是一個「生的」、尚未初始化的物件。
步驟二:初始化。呼叫 init 開頭的方法。帶參數或不帶參數的各種 init 都算在內。初始化成功就回傳物件本身,失敗則回傳 nil。另外有個細節:如果某個類別沒有實作自己的 initializer,runtime 會往上找到最近的那個祖先類別的 initializer 來呼叫。
透過上述方式建立的物件,其返回值需要送進自動管理池(autorelease pool)裡。
題目給定的方法簽章如下:
+ (id)initWithCString:(const char *)nullTerminatedCString
encoding:(NSStringEncoding)encoding;要求實作的是工廠方法版本:
+ (id) stringWithCString: (const char*)nullTerminatedCString
encoding: (NSStringEncoding)encoding
{
NSString *obj;
obj = [self allocWithZone: NSDefaultMallocZone()];
obj = [obj initWithCString: nullTerminatedCString encoding: encoding];
return AUTORELEASE(obj);
}這段程式碼剛好把上面的理論完整演練了一次:先 allocWithZone: 配置記憶體,再 initWithCString:encoding: 初始化,最後 AUTORELEASE 交給自動管理池。三步驟一氣呵成,考官想看的正是你對這個流程的熟悉度。
A convention in Cocoa programming is to nest the allocation call inside the initialization call.
MyCustomClass *myObject = [[MyCustomClass alloc] init];也就是把 alloc 直接嵌在 init 裡面。這是 Cocoa 社群的公約,理由是它讓「配置」與「初始化」在視覺上成為一個不可分割的整體,也避免出現 alloc 之後忘了 init 就使用的危險寫法。
+ (id)dataWithContentsOfURL:(NSURL *)url;這類以類別名稱開頭、回傳 id 的方法就是便利建構子,也常被稱為工廠方法。它的特點是:回傳的物件已經是 autoreleased 狀態,使用者不需要(也不應該)再對它做 release。這也是為什麼在 ARC 之前的年代,「new、alloc、copy、mutableCopy 開頭的方法你要自己管,其他一律不用管」會被當成記憶體管理的口訣。