【问题标题】:What is the meaning of init method in objective c?目标c中的init方法是什么意思?
【发布时间】:2016-12-18 01:23:00
【问题描述】:

我是objective c的新手,来自java背景,我想知道在实现继承的同时,objective c中的init()方法/函数是什么意思? 这是一种像java中的构造函数吗?是否必须仅使用 init() 方法来创建和使用对象?我们可以使用其他方法来代替init()吗?

最后,为什么init()的返回类型是id

【问题讨论】:

标签: objective-c


【解决方案1】:

所以如果它是目标 c,它是 init 而不是 init() :) 只是说......有点大事...... 在java中查看,当你在做一个

new MyClass()

发生了两件事:

  • 编译器会在内存中预留一些空间来存储新实例
  • 调用了 MyClass 构造函数。

现在,在 Objective-C 中,这两件事被分成 2 种方法: - 分配 - 初始化

所以当你确实想创建一个新对象时,你必须调用这两个方法

MyClass * a = [MyClass alloc]; // this will return a pointer to a space in memory big enough to store an instance of MyClass
a = [a init]; // this will call the init method on a and return the pointer initialized with all iVar to 0 plus whatever you did by yourself in the init method.

通常,它是在一行中完成的

MyClass * a = [[MyClass alloc] init];

这就是为什么初始化一个返回实际实例的实例类如此方便的原因

【讨论】:

    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多