Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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()?

like image 816
Rob Jones Avatar asked Jan 06 '10 22:01

Rob Jones


People also ask

How do you call an init method in Objective C?

Whenever an object is "created" by default it is supposed to be done with myObject=[[MyObjectClass alloc]init] or the equivalent shortcut myObject=[MyObjectClass new] . That is where your init method is called.

What is init in Objective C?

Out of the box in Objective-C you can initialize an instance of a class by calling alloc and init on it. // Creating an instance of Party Party *party = [[Party alloc] init]; Alloc allocates memory for the instance, and init gives it's instance variables it's initial values.

What is the importance of init () method in Apple?

init() Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.


2 Answers

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.

like image 55
Rob Napier Avatar answered Sep 19 '22 21:09

Rob Napier


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

Link

like image 45
psychotik Avatar answered Sep 17 '22 21:09

psychotik