Reputation: 33624
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];
Upvotes: 3
Views: 1847
Reputation: 3851
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.
Upvotes: 4
Reputation: 37494
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];
Upvotes: 2