views:

63

answers:

3

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];
+1  A: 

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];
luvieere
what are you trying to do here? `myStr`, `str1` and `str2` will all point to the same string object, ie only the last initialization is relevant
Christoph
I agree with christoph, not only that, but if you made any changes to the internal structure of str1 that are not overwritten by initWith format: between init and initWithFormat: those changes will still be there.
Elfred
No, you can't do that. I mean, you can write it, but it's **totally wrong**. Also, whether `myStr`, `str1` and `str2` point to the same string is implementation-dependent. In most implementations, they will be different objects when you do this with NSString or any other class cluster, but will be the same object for other classes.
Chuck
+4  A: 

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.

Elfred
+2  A: 

Nope, no difference.

Kevin Sylvestre