Cocoa Core Competencies 的Object creation 和IOS面试题示例:写

来源:未知 责任编辑:责任编辑 发表时间:2013-11-26 22:12 点击:

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;

    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • Lexical or Preprocessor Issue 'xxx.h
    • ios学习笔记(二)xcode 4.3.2下实现基本交互
    • ios版本的helloworld
    • iphone(object-c) 内存管理(3) 有效的内存管理 前半部分
    • ios学习笔记(一)xcode 4.3.2下创建第一个ios项目
    • IOS类似iphone通讯录TableView的完整demo【附源码】
    • UITableView一些方法
    • [iPhone中级]iPhone团购信息客户端的开发 (二)
    • 如何为Iphone应用创建启动界面
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1