如何用“超类的现有对象"初始化子类的对象;在Objective-C中 [英] how to initialize an object of subclass with an "existing object of superclass" in objective-C

查看:52
本文介绍了如何用“超类的现有对象"初始化子类的对象;在Objective-C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将NSException类子类化以创建CustomException类.

I have subclassed NSException class to create CustomException class.

每当我在代码中(在@catch中)捕获到异常时,我都想使用NSException对象作为参数传递给@catch来初始化CustomException(NSException的子类)对象.

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.

类似这样的东西

@catch (NSException * e) {

CustomException * ex1=[[CustomException alloc]initWithException:e errorCode:@"-11011" severity:1];
}

我尝试通过将NSException对象传递给CustomException的init方法来做到这一点. (我用传递的NSException对象替换了[super init],如下所示)

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?

预先感谢

推荐答案

您正在尝试做通常在任何OO语言中都不支持[*]的操作-将类的实例转换为其类之一的实例子类.

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.

您的赋值self=originalException只是(类型不正确)指针赋值(当您使用id作为类型时,编译器和运行时将检查该指针赋值)-这不会CustomException中的CustomException.

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.

要实现所需的目标,请替换为self=originalException

To achieve what you want replace self=originalException with

[super initWithName:[originalException name]
       reason:[originalException reason]
       userInfo:[originalException userInfo]]

,然后继续初始化您在CustomException中添加的字段.

and then continue to initialize the fields you've added in CustomException.

[*]在Objective-C中,在某些情况下可以 正确地将类实例转换为子类实例,但是不要这样做非常非常好的理由.而且,如果您不知道自己该怎么想,;-)

[*] 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 ;-)

这篇关于如何用“超类的现有对象"初始化子类的对象;在Objective-C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆