search

Home  >  Q&A  >  body text

objective-c - objective c如何new一个对象?

这里我是指不使用框架,纯粹的objective-c语法是如何新建一个对象的?

我在网上查了许多资料,都是用NSObject的alloc后再init的方法创建一个对象
难道objective c这个语言要新建对象还必须依赖某个框架或者某个父类的存在?这不合逻辑啊

PHP中文网PHP中文网2769 days ago731

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-21 10:59:52

    使用class_createInstance
    官方文档里内容:
    Creates an instance of a class, allocating memory for the class in the default malloc memory zone.

    id class_createInstance(Class cls, size_t extraBytes)
    Parameters
    cls
    The class that you wish to allocate an instance of.
    extraBytes
    An integer indicating the number of extra bytes to allocate. The additional bytes can be used to store additional instance variables beyond those defined in the class definition.
    Return Value
    An instance of the class cls.

    Declared In
    runtime.h

    参考资料
    http://developer.apple.com/library/ma...

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-21 10:59:52

    obj-c has two ways to create objects

    • Initialization, first call the alloc method to apply for memory, and then call the init method to create the object.
    • Construction method, directly call the static construction method to create the object. This method is actually just a wrapper for initialization.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-21 10:59:52

    I am currently learning iPhone development. The book says that Objective-C separates the steps of instantiating a class.
    alloc is used to allocate memory space, and then initialized with init or other methods, such as:

    myArray = [[NSArray alloc] initWithObjects:@"张二",@"张三", nil];

    reply
    0
  • Cancelreply