Objective-C中的对象声明

Objective-C中的对象声明,objective-c,object,declaration,Objective C,Object,Declaration,在Objective-C中,除了风格和个人偏好之外,(1)和(2)在声明对象方面有什么区别吗 (1)单行声明、分配、初始化。 Student *myStudent; myStudent = [Student alloc]; myStudent = [myStudent init]; Student*myStudent=[[Student alloc]init] (2)多行声明、分配、初始化。 Student *myStudent; myStudent = [Student alloc];

在Objective-C中,除了风格和个人偏好之外,(1)和(2)在声明对象方面有什么区别吗

(1)单行声明、分配、初始化。

Student *myStudent;
myStudent = [Student alloc]; 
myStudent = [myStudent init];
Student*myStudent=[[Student alloc]init]

(2)多行声明、分配、初始化。

Student *myStudent;
myStudent = [Student alloc]; 
myStudent = [myStudent init];

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

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

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

如果您熟悉C,请将alloc视为

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

init调用是一个设置初始值的函数。

不,没有区别。

您在这里想做什么
myStr
str1
str2
都将指向同一个字符串对象,即只有最后一次初始化是相关的,我同意christoph,不仅如此,但是如果您对str1的内部结构做了任何没有被initWithFormat覆盖的更改:在init和initWithFormat之间:这些更改仍然存在。不,您不能这样做。我是说,你可以写,但它完全错了。此外,myStr、str1和str2是否指向同一字符串取决于实现。在大多数实现中,当您使用NSString或任何其他类集群执行此操作时,它们将是不同的对象,但对于其他类,它们将是相同的对象。