我应该如何处理Objective-C中init:方法的失败? [英] How should I handle a failure in an init: method in Objective-C?
问题描述
假设我在Objective-C中为iPhone构建一个新类。在我的一个init方法中,我想手动分配一些内存。所以,我可能有这样的事情:
Let's say I'm building a new class for the iPhone in Objective-C. In one of my init methods I want to manually allocate some memory. So, I might have something like this:
- (id)initWithSomeObject:(SomeObject *)someObject {
self = [super init];
if (self != nil) {
myObject = someObject;
[myObject retain];
if ( (memory = calloc(1, sizeof(SomeStruct)) == NULL) {
// What should I do here to clean up
[self release];
self = nil;
}
}
return self;
}
现在,假设calloc()可能失败,并且无法分配内存对我的对象来说是灾难性的,我应该在if-body内做什么来正确清理?是否有Objective-C成语或者我应该使用的模式?
Now, assuming that the calloc() could fail, and that failing to allocate memory is catastrophic for my object, what should I do inside the if-body to clean up properly? Is there an Objective-C idiom or pattern that I should be using?
编辑:我包含了Rob Napier发布的代码。但是,我还是要发布myObject,对吧?或者添加的代码不知何故触发dealloc()?
I included the code posted by Rob Napier. But, I still have to release myObject, right? Or does the added code somehow trigger dealloc()?
推荐答案
是的,你应该释放自己,然后返回 nil
。
Yes, you should release yourself and then return nil
.
[self release];
self = nil;
请参阅初始化器的问题。
这篇关于我应该如何处理Objective-C中init:方法的失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!