how to initialize an object of subclass with an “existing object of superclass” in objective-C

筅森魡賤 提交于 2020-01-15 14:45:47

问题


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 a NSException object ;(

  • After that, the compiler will think that self is a CustomException object so it won't complain when calling some methods of CustomException 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

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