How should I handle a failure in an init: method in Objective-C?

不羁岁月 提交于 2019-12-03 23:21:01

问题


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;
}

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?

Edit: I included the code posted by Rob Napier. But, I still have to release myObject, right? Or does the added code somehow trigger dealloc()?


回答1:


Yes, you should release yourself and then return nil.

[self release];
self = nil;

See Issues with Initializers in the Concepts in Objective-C Programming guide.




回答2:


You need to clean up anything you need to and then set the self reference to nil. Apple Dev Portal has an article:

Link




回答3:


I just tried. -dealloc gets called due to [self release], so myObject would not need to get released in initWithSomeObject. To be sure, you might move myObject = [someObject retain]; (I prefer that style in case -retain might fail for some reason) below the call that might fail (if that's possible).



来源:https://stackoverflow.com/questions/2016795/how-should-i-handle-a-failure-in-an-init-method-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!