面试题总结

来源:互联网 发布:matlab 矩阵转cell 编辑:程序博客网 时间:2024/06/08 08:26

1.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.

对象的创建过程:

一个对象进入到runtime的生存周期经过两个过程:分配对象的内存和将它设置一个合理的初始化值。为了分配一个Objective-C对象,发送alloc或者allocWithZone消息:针对对象的类。在runtime分配内存给对象并返回一个“raw”(未被初始化的)类的例子。同时也分配一个指针(众所周知就是isa指针)给对象的类,清空所有的实例变量到一个适当的类型值,同时将对象的retain count置为1。


当你分配一个对象内存的时候,你必须要初始化它。初始化将对象的实例变量置为一个合理的初始化值。同时分配和预备对象需要的其他全局资源。你初始化一个对象通过调用init方法或者其他带有init开头名字的方法。这些初始化方法通常有一个或多个参数能够使你确定对象的实例变量的初始值(文档也是写的成员变量和实例变量是一回事)。如果这些方法成功地初始化一个对象,它们将返回对象本身。否则将返回nil。如果一个对象的类并没有实现初始化,Objective-C的runtime机制自动调用它最近的祖先类的初始化来代替。(这个也就是为啥if(self=[super init])的存在呗)


1.写一个NSString的类实现:

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

通过上面对象创建和实例的基础后应该不难理解啦。值得注意的是这两个方法都是iOS的NSString方法来的。



0 0
原创粉丝点击