Subject: Re: Is "-init" really needed?



I don’t have a problem with using “new” vs. alloc/init, but there are a couple
of technical issues hiding behind this, though in current practice they make
little difference.

1. NSObject has “new” with a standard meaning. That means you can use “new” on
any subclass where it’s OK to use the simple “init” without parameters.
However, for classes that need parameters, or have multiple inits, there’s no
standard “newWithX:…” class method unless you provide it yourself.

You can’t really provide this for Cocoa classes (you could try adding it via a
category, but this seems like a bad idea), which means your code uses a mixture
of strategies to create instances, even of the same class, depending on the
parameters needed. If that doesn’t bother you, fine. This is purely a matter of
preference.

2. In modern Obj-C, a class method beginning with “new…” is specially
meaningful to the compiler under ARC. By default, it has +1 ownership semantics
for the returned reference. Using Jens’ earlier example, that means that the
following are subtly different:

> [NSArray array] // +0 semantics
> [NSArray new] // +1 semantics

For custom “new…” methods, the declaration can override the default semantics
with a compile-time attribute, which means you cannot in general be certain of
the semantics without looking at the declaration.

Of course, if the *calling* code is also ARC, then it doesn’t matter, because
ARC keeps track of the semantics for you.

So, as I said, little practical difference.
_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Co...

ntact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/maillists%40codeha.us

This email sent to [email protected]



Programming list archiving by: Enterprise Git Hosting