开发者

Calling new for allocation objects in Objective-C [duplicate]

开发者 https://www.devze.com 2023-04-11 21:37 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Use of alloc init instead of new (Objective-C)
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Use of alloc init instead of new (Objective-C)

开发者_高级运维Does any of you use +new of the NSObject to alloc & init the object?

Lets say i got an object C derived from Object B which all are from NSObject. To create an instance of Object C

C newInstanceOfC = [C new]; // This will call the alloc & init of class C.

is this any better than

C newInstanceOfC = [C alloc] init];

other than less things to type. What is good practice?

cheers Arun


alloc] init] is best practice. In particular, objects have different ways to init, including zero, one or more than one parameter. Using new makes an automatic selection of init, but having init visible can help you troubleshoot some nasty bugs that can happen if you initialise a UI element but forget to set the frame, etc.. You'll get compiler warnings about the use of the init method in some circumstances too.


They are both exactly the same, new is the new way, as that wasn't possible before, but use the one that you like the most.

I usually use new since it is shorter, although in several cases you can't since you usually want to do something like:

[[myObject] alloc] initWith...];
0

精彩评论

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