What happens to alloc if initWithX fails?
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 开发者_JAVA百科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.
Basically, this answers your question.
Handling Initialization Failure
In general, if there is a problem during an initialization method, you should call the
release
method onself
and returnnil
.There are two main consequences of this policy:
- Any object (whether your own class, a subclass, or an external caller) that receives
nil
from an initializer method should be able to deal with it. In the unlikely case that the caller has established any external references to the object before the call, you must undo any connections.- You must make sure that
dealloc
methods are safe in the presence of partially initialized objects....
精彩评论