Cocoa Core Competencies 的Object creation 和IOS面試題示例:寫一個NSString類的實現 – iPhone手機開發技術文章 iPhone軟體開發教學課程

object creation:
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.

意思是:建立對象需要兩個步驟1分配內存 2初始化

1分配內存,要sent alloc orallocWithZone: message to the object’s class. 也就是常見的[Class alloc].或是不常見的[Class allocWithZone]

2初始化.要調用init的方法進行初始化,各種各樣的要或不要參數的init方法都算.

以上建立對象的方式,返回值要送進 對象自動管理池

IOS面試題示例:寫一個NSString類的實現

 

+ (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);
}

The Form of an Object-Creation Expression

A convention in Cocoa programming is to nest the allocation call inside the initialization call.

MyCustomClass *myObject = [[MyCustomClass alloc] init];
便利函數:就是工廠方法,不需使用者管理.
+ (id)dataWithContentsOfURL:(NSURL *)url;

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。