Cocoa Core Competencies Object creation and IOS interview question example: write an implementation of NSString class

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.

Means: two steps are required to create an object: 1 allocate memory and 2 initialize

1 To allocate memory, send  alloc or allocWithZone: message to the object's class. That is the common [Class alloc]. Or the uncommon [Class  allocWithZone]

2 Initialization. To call the init method for initialization, all kinds of init methods with or without parameters are counted.

The above method of creating an object, the return value should be sent to the object automatic management pool

iOS interview question example: write an implementation of NSString class



+ (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];

Convenience function: It is a factory method and does not require user management.

+ (id)dataWithContentsOfURL:(NSURL *)url;

Guess you like

Origin blog.csdn.net/wu347771769/article/details/73132176