开发者

Object declaration in Objective-C

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, initializati开发者_运维知识库on.

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

(2) Multi-line declaration, allocation, initialization.

Student *myStudent;
myStudent = [Student alloc]; 
myStudent = [myStudent 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.


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];


Nope, no difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜