It is common practice to write MyClass* obj = [[MyClass alloc] initWithX:X]
in Objective-C. initWithX
is usually defined as
- (MyClass*) initWithX: (MyArgClass*) X {
if (self = [super init]) {
// initialize
}
return self;
}
My question is: what if initialize fails? I don't want to throw exceptions, but, how do I indicate error? If I return nil
, the caller will not be able to release the pointer.
If initialization fails for any reason you should release self. For an exception that may occur in your initialization you need to add you @try
@catch
as appropriate so you can release self
.
- (MyClass*) initWithX: (MyArgClass*) X {
if (self = [super init]) {
// initialize
if(myInitializationCodeFailed)
{
[self release];
return nil;
}
}
return self;
}
Update
If it is possible for your initialization fail I would not raise an exception from with in your initialization code. If you would like to provide the caller with information I would refactor the initializer to accept an NSError
to be returned.
- (MyClass*) initWithX: (MyArgClass*) X error:(NSError**)error {
As Alexei Sholik points in the comments check out the Handling Initialization Failure section of Allocating and Initializing Objects.