问题
I have subclassed NSException class to create CustomException class.
Whenever I catch an exception in code (in @catch), i want to initialize an object of CustomException (subclass of NSException) with the object of NSException that is passed as a parameter to @catch.
Something like this
@catch (NSException * e) {
CustomException * ex1=[[CustomException alloc]initWithException:e errorCode:@"-11011" severity:1];
}
I tried doing it by passing the NSException object to the init method of CustomException. (i replaced the [super init] with the passed NSException object as given below)
//initializer for CustomException
-(id) initWithException:(id)originalException errorCode: (NSString *)errorCode severity:(NSInteger)errorSeverity{
//self = [super initWithName: name reason:@"" userInfo:nil];
self=originalException;
self.code=errorCode;
self.severity=errorSeverity;
return self;
}
This doen't work! How can I achieve this?
Thanks in advance
回答1:
You are trying to do something which generally[*] isn't supported in any OO language - convert an instance of a class into an instance of one of its subclasses.
Your assignment self=originalException
is just (type incorrect) pointer assignment (which the compiler and runtime will not check as you've used id
as the type) - this won't make CustomException
out of an NSException
.
To achieve what you want replace self=originalException
with
[super initWithName:[originalException name]
reason:[originalException reason]
userInfo:[originalException userInfo]]
and then continue to initialize the fields you've added in CustomException
.
[*] In Objective-C it is possible in some cases to correctly convert a class instance into a subclass instance, but don't do it without very very very very good reason. And if you don't know how you shouldn't even be thinking of it ;-)
回答2:
self = originalException;
When you do that you are just assigning a NSException
object to your NSCustomException
so
the following things will happen:
You might get a warning when doing the assignment since
CustomException
is expected but you are passing just aNSException
object ;(After that, the compiler will think that
self
is aCustomException
object so it won't complain when calling some methods ofCustomException
class but it will crash when reaching those.
You should enable initWithName:reason:userinfo:
and don't do the assignment.
来源:https://stackoverflow.com/questions/4872155/how-to-initialize-an-object-of-subclass-with-an-existing-object-of-superclass