Objective-C 中的对象声明

发布于 2024-09-05 05:30:37 字数 311 浏览 4 评论 0原文

除了风格和个人喜好之外,(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

∞琼窗梦回ˉ 2024-09-12 05:30:37

不,没有区别。 [Student alloc]只是为指针分配内存,同时[myStudent init]实际上设置了初始值。

如果您熟悉 C,可以将 alloc 视为正在执行

Student *myStudent = calloc(1, sizeof(Student));

并将 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

Student *myStudent = calloc(1, sizeof(Student));

And the init call as a function that sets the initial values.

Smile简单爱 2024-09-12 05:30:37

在第二种情况下,您可以多次初始化同一个对象。您向类发送一条 alloc 消息来获取一个未初始化的实例,然后您必须初始化该实例,有多种方法可以实现:

NSString *myStr = [NSString alloc];
NSString *str1 = [myStr init]; //Empty string
NSString *str2 = [myStr initWithFormat:@"%@.%@", parentKeyPath, key];

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:

NSString *myStr = [NSString alloc];
NSString *str1 = [myStr init]; //Empty string
NSString *str2 = [myStr initWithFormat:@"%@.%@", parentKeyPath, key];
把时间冻结 2024-09-12 05:30:37

不,没有区别。

Nope, no difference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文