【问题标题】:how to initialize an object of subclass with an "existing object of superclass" in objective-C如何在Objective-C中用“超类的现有对象”初始化子类的对象
【发布时间】:2011-06-19 19:39:58
【问题描述】:

我有子类 NSException 类来创建 CustomException 类。

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

类似的东西

@catch (NSException * e) {

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

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

//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;
}

这行不通!我怎样才能做到这一点?

提前致谢

【问题讨论】:

    标签: objective-c inheritance subclass init superclass


    【解决方案1】:

    您正在尝试做一些通常 [*] 不受任何 OO 语言支持的事情 - 将类的实例转换为其子类之一的实例。

    您的分配 self=originalException 只是(类型不正确)指针分配(编译器和运行时将检查您已使用 id 作为类型) - 这不会CustomException 来自NSException

    为了实现你想要的替换 self=originalException

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

    然后继续初始化你在CustomException中添加的字段。


    [*] 在 Objective-C 中 在某些情况下可以正确地将类实例转换为子类实例,但 不要这样做 非常非常非常非常好的理由。如果你不知道你甚至不应该去想它;-)

    【讨论】:

    • OO 不支持将父具体类型向下转换为子类型。但是,这个问题是在谈论复制。在 C++ 中,您可以这样回答这个问题:cpp.sh/3ar6m
    【解决方案2】:
    self = originalException;
    

    当你这样做时,你只是将一个 NSException 对象分配给你的 NSCustomException 所以 会发生以下事情:

    • 执行此操作时可能会收到警告 从那时起的任务 CustomException 是预期的,但你 正在传递一个NSException 对象;(

    • 之后,编译器会认为self 是一个CustomException 对象所以它 打电话时不会抱怨 CustomException 类的方法 但是到达时会崩溃 那些。

    您应该启用initWithName:reason:userinfo: 并且不要执行分配。

    【讨论】:

      猜你喜欢
      • 2014-10-07
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 2017-02-15
      • 2018-09-15
      相关资源
      最近更新 更多