On 29 Nov 2010, at 6:59 PM, Rainer Standke wrote:
> I am thinking about doing something like this:
>
> - to init a custom object, call a convenience initializer that in turn calls
> the designated initializer
>
> - in the convenience initializer, before the designated initializer is
> called, check some conditions. If that test fails return nil.
>
> The intended behavior is not to get anything if the conditions are not met.
>
>
> Is this kosher? Do I have to do any kind of clean-up after doing something
> like that?
Yes, this is kosher. The -init methods aren't magic (unlike a C++ constructor);
they are simply the conventional way for a blank object returned by +alloc to
be made useful.
You'll need to make sure that the allocated and partially-initialized object is
deallocated, which is usually as simple as calling [self release] before
returning nil. In your -dealloc method, of course, you must not do anything
that will fail if -dealloc is called on an object that wasn't completely
initialized. (If you're just sending -release to objects you own, you normally
don't have to do anything differently, since their uninitialized value will be
'nil' and sending -release to nil is OK. But if you call free() or CFRelease(),
or follow pointers, etc., you will need to be more careful.)
If you *subclass* a class that does funny stuff in its init method, you also
need to deal with it. If -init may simply return nil, my usual idiom is:
if (![super init])
return nil;
...continue with normal initialization...
and of course your subclass's -dealloc may be called on a partially-constructed
object as well.
If the superclass's init may return an object other than self --- if, for
example, you've implemented a class-cluster, or an init method that enforces
uniqueness/sharing among objects --- then you might need to assign the result
of [super init] to self. However, at that point 'self' may no longer refer to
an object of the expected class, or may be an instance that is already fully
initialized. This can get confusing, and I think it's better to avoid
overriding the init method at all in that situation.
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]