2014年3月7日金曜日

クラスの内容をファイルに出力する方法(3)

さて、先の入出力関数の中では、NSArrayの中に別のクラスが存在する場合はそのまま処理できない。
それも入出力する場合は、そのクラスの中に少し処理を追加する必要がある。

追加するのはcoderという処理。これを入れるとクラスをNSDataにシリアライズして入出力出来るようになる。

以下のように実装する。


こんなクラスの場合↓
@interface TestClass : NSObject
{
    int     testInt;
    float   testFloat;
    NSArray *testArray;
}

こういうふうに実装する↓。

- (void)encodeWithCoder:(NSCoder *)aCoder
{
//  NSLog(@"encodeWithCoder");
    // メンバーのそれぞれをencode*:forKeyで変換する
    // キー名は適当でいいけど、基本はメンバー名と同じにすればいいと思う
    [aCoder encodeObject:testArray    forKey:@"testArray"];
    [aCoder encodeInt:testInt         forKey:@"testInt"];
    [aCoder encodeDouble:testFloat    forKey:@"testFloat"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
//  NSLog(@"initWithCoder");
    self = [super init];
    if (self!=nil) {
        // メンバーのそれぞれをdecode*ForKeyで逆変換する
        // キー名はencodeで指定したもの
        testArray    = [aDecoder decodeObjectForKey: @"testArray"];
        testInt      = [aDecoder decodeIntegerForKey:@"testInt"];
        testFloat    = [aDecoder decodeDoubleForKey: @"testFloat"];
    }
    return self;
}

-(NSString *)description
// %@で表示するための文字列を返す処理
// これは必須ではない
{
    return [NSString stringWithFormat:
            @"< %@ : %p >"
            @"testArray=%@ ,"
            @"testInt=%u ,"
            @"testFloat=%f ,"
            ,NSStringFromClass([self class]),self
            ,testArray
            ,testInt
            ,testFloat
            ];
    // 再帰呼び出しになるので、"%@",selfは記述してはいけない
}

上記のメソッドを、出力したいクラスの@implementationの中に追加する。
なお、coderはカテゴリでは実装できない(無視される)。
また、coderを実装しただけでは[ary writeToFile]では出力されない様子である。









0 件のコメント:

コメントを投稿