Calling new for allocation objects in Objective-C [duplicate]
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...];
精彩评论