如果 initWithX 失败,分配会发生什么情况?
在 Objective-C 中编写 MyClass* obj = [[MyClass alloc] initWithX:X]
是常见的做法。 initWithX
通常定义为
- (MyClass*) initWithX: (MyArgClass*) X {
if (self = [super init]) {
// initialize
}
return self;
}
我的问题是:如果初始化失败怎么办?我不想抛出异常,但是,如何指示错误?如果我返回nil,调用者将无法释放指针。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果初始化由于任何原因失败,你应该释放 self.对于初始化过程中可能发生的异常,您需要根据需要添加
@try
@catch
以便您可以释放self
。更新
如果您的初始化可能失败,我不会在您的初始化代码中引发异常。如果您想向调用者提供信息,我将重构初始化程序以接受
NSError
返回。正如 Alexei Sholik 在评论中指出的那样,请查看 分配和初始化对象的处理初始化失败部分。
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 releaseself
.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.As Alexei Sholik points in the comments check out the Handling Initialization Failure section of Allocating and Initializing Objects.
基本上, 这回答了你的问题。
Basically, this answers your question.