1

NSExceptionクラスをサブクラス化して、CustomExceptionクラスを作成しました。

コード(@catch内)で例外をキャッチするたびに、CustomExceptionのオブジェクト(NSExceptionのサブクラス)を、パラメーターとして@catchに渡されるNSExceptionのオブジェクトで初期化します。

このようなもの

@catch (NSException * e) {

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

NSExceptionオブジェクトをCustomExceptionのinitメソッドに渡してみました。([super init]を、以下に示すように、渡されたNSExceptionオブジェクトに置き換えました)

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

これは機能しません!どうすればこれを達成できますか?

前もって感謝します

4

2 に答える 2

0
self = originalException;

NSExceptionこれを行うと、オブジェクトをに割り当てるだけNSCustomExceptionなので、次のことが起こります。

  • が期待されているため、割り当てを行うときに警告が表示 CustomExceptionされる場合がありますが、オブジェクトだけを渡していNSException ます;(

  • その後、コンパイラはそれselfCustomExceptionオブジェクトと見なすため、クラスのいくつかのメソッドを呼び出すときに文句を言うことはありませんが、CustomExceptionそれらに到達するとクラッシュします。

割り当てを有効initWithName:reason:userinfo:にし、実行しないでください。

于 2011-02-02T08:41:48.427 に答える
0

一般に [*] どの OO 言語でもサポートされていないことをしようとしています - クラスのインスタンスをそのサブクラスの 1 つのインスタンスに変換します。

あなたの代入self=originalExceptionは単なる(型が正しくない)ポインタの代入です(型として使用したため、コンパイラとランタイムはチェックしませんid -これCustomExceptionNSException.

あなたが望むものを達成するためself=originalException

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

で追加したフィールドの初期化を続けますCustomException


[*] Objective-C では、クラス インスタンスをサブクラス インスタンスに正しく変換できる場合がありますが、非常に正当な理由がない限り、変換しないでください。そして、あなたがそれを考えてはいけない方法がわからない場合;-)

于 2011-02-02T09:29:25.143 に答える