views:

259

answers:

3

In Delphi, is normal do this:

ob = TObject.create;
try
  //code
finally
  ob.free;
end;

I wonder if that is similar in Obj-c.

+1  A: 

No. Objective-C does support exceptions and you see them in Cocoa infrequently (NSError is the direction Apple is headed) but you definitely wouldn't use them every time you initialize or release an object.

Marc Charbonneau
+1  A: 

I'm certainly no expert in Obj-C but the fact that it provides (what people have asked in Delphi) the compound try/catch/finally, gives you the choice to use that to program defensively like in Delphi:

@try {
   // protected block
} 
@catch (id theException) {
  // do smthing with theException
} 
@finally {
  // clean up code 
}

And I would argue that if programmers used the @finally more often, there would be less bugs in their developments.

François
The problem is, as noted, this has a performance cost. I am a former Java developer and used that pattern all the time myself - but in Objective-C, it's just not usually helpful as few things throw exceptions and Obj-C coders are not used to using them.
Kendall Helmstetter Gelner
+3  A: 

You could do it that way, but exceptions tend to have a high cost in Objective-C. There are some differences in their performance between the 32-bit and 64-bit ABIs, as well as the interaction between Objective-C exceptions and C++ exceptions.

An alternative is to create your objects such that they are autoreleased and only retain them before your method ends.

SomeClass *object = [[[SomeClass alloc] init] autorelease];

/* deadly code here */

return [object retain];

This way even if your code experiences an exception your object will be released the next time the autorelease pool is drained (usually at the end of the event loop), assuming that the exception is not fatal and causes your program to crash.

Apple has some documentation about Obj-C exceptions and the release notes for Leopard towards the end discuss the changes in the 64-bit ABI.

Ashley Clark