[cfe-dev] Objc, cannot cast 'super' error

David Chisnall csdavec at swan.ac.uk
Sun Jul 3 04:55:45 PDT 2011


On 3 Jul 2011, at 12:15, Dave Keck wrote:

>    3. Make MyProtocol an informal protocol on NSObject instead.
> 
>        This option is bad because a formal protocol is the correct
> abstraction for my use-case.


No it isn't.  If you are explicitly sending messages that a class does not respond to then an informal protocol is exactly what you want.  

Note that there is nothing stopping you from using both a formal and informal protocol, if you wish for explicit testing.

Using these exceptions is very bad style for several reasons:

1) Exceptions in Objective-C are intended to indicate programmer error and are very slow.  Using them for a recoverable error is bad.

2) You are overloading the meaning of an exception, making it difficult to distinguish between a real error and this error.

3) Code that assumes 1) (i.e. most Cocoa code, including code compiled with ARC enabled) will leak memory if it's in any intervening stack frames.

If you really must use exceptions, a better way of doing it would be something like:

@implementation NSObject (MyProtocol)
- (void)handleToken: (id) token
{
	NSString *reason = [NSString stringWithFormat: @"Unhandled token %@", token];
	NSDictionary *userInfo = [NSDictionary dictionaryWithObject: token
	                                                     forKey: kMyProtocolUnhandledToken]
	[[NSException exceptionWithName: MyProtocolUnhandledTokenException
	                         reason: reason
	                       userInfo: userInfo] raise];
}
@end

This would then ensure that you had a meaningful exception to catch, rather than doing something ugly and hackish.  

David

--
This email complies with ISO 3103



More information about the cfe-dev mailing list