Objective-C 中的对象声明
除了风格和个人喜好之外,(1) 和 (2) 在 Objective-C 中声明对象还有什么区别吗?
(1) 一行声明、分配、初始化。
Student *myStudent = [[Student alloc] init];
(2) 多行声明、分配,初始化。
Student *myStudent;
myStudent = [Student alloc];
myStudent = [myStudent init];
Is there any difference in declaring objects in Objective-C between (1) and (2), besides the style and personal preference?
(1) One-line declaration, allocation, initialization.
Student *myStudent = [[Student alloc] init];
(2) Multi-line declaration, allocation, initialization.
Student *myStudent;
myStudent = [Student alloc];
myStudent = [myStudent init];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,没有区别。 [Student alloc]只是为指针分配内存,同时[myStudent init]实际上设置了初始值。
如果您熟悉 C,可以将 alloc 视为正在执行
并将 init 调用视为设置初始值的函数。
No, there isn't a difference. The [Student alloc] just allocates memory for a pointer, meanwhile [myStudent init] actually sets the initial values.
If you are familiar with C, think of alloc as doing
And the init call as a function that sets the initial values.
在第二种情况下,您可以多次初始化同一个对象。您向类发送一条
alloc
消息来获取一个未初始化的实例,然后您必须初始化该实例,有多种方法可以实现:In the second case, you can initialize the same object more than once. You send an
alloc
message to the class to get an uninitialized instance, that you must then initialize, having several ways to do it:不,没有区别。
Nope, no difference.