48

私のクラスには、nibファイルをロードしてオブジェクトをインスタンス化するための次のメソッドがあります。

- (id)initWithCoder:(NSCoder*)aDecoder 
{
    if(self = [super initWithCoder:aDecoder]) {
        // Do something
    }
    return self;
}

このクラスのオブジェクトをどのようにインスタンス化しますか?これは何NSCoderですか?どうすれば作成できますか?

    MyClass *class = [[MyClass alloc] initWithCoder:aCoder];
4

2 に答える 2

41

また、次のメソッドを次のように定義する必要があります。

- (void)encodeWithCoder:(NSCoder *)enCoder {
    [super encodeWithCoder:enCoder];

    [enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY];

    // Similarly for the other instance variables.
    ....
}

そして、initWithCoderメソッドで次のように初期化します。

- (id)initWithCoder:(NSCoder *)aDecoder {

   if(self = [super initWithCoder:aDecoder]) {
       self.instanceVariable = [aDecoder decodeObjectForKey:INSTANCEVARIABLE_KEY];

       // similarly for other instance variables
       ....
   }

   return self;
}

オブジェクトを標準的な方法で初期化できます。

CustomObject *customObject = [[CustomObject alloc] init];
于 2010-10-15T15:57:50.737 に答える
18

このNSCoderクラスは、オブジェクトのアーカイブ/アーカイブ解除(マーシャル/アンマーシャル、シリアル化/逆シリアル化)に使用されます。

これは、ストリーム(ファイル、ソケットなど)にオブジェクトを書き込み、後でまたは別の場所でオブジェクトを取得できるようにする方法です。

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/Archiving/Archiving.htmlを読むことをお勧めします

于 2010-10-15T15:47:04.717 に答える