0

私は不変のクラスを作ろうとしています。難しい話は抜きにして:

#import "MatrixRow2.h"

@implementation MatrixRow2

@synthesize rows;

-(MatrixRow2*) initWithFractionNumberArray:(NSArray*)array
{
    if (self = [super init]) {
        rows = array;
    }

    return self;
}

-(MatrixRow2*) rowByMultiplyingByFractionNumber:(FractionNumber*)number
{
    NSArray *temp = rows.copy;
    MatrixRow2 *newRow = [[MatrixRow2 alloc] initWithFractionNumberArray:temp];

    for (int i=0; i < newRow.rows.count; i++) {
        [[newRow.rows objectAtIndex:i] multiplyByFraction:number];
    }

    return newRow;
}

-(NSString*) description
{
    return [rows description];
}

@end

そしてテスターコード:

MatrixRow2 *r = [[MatrixRow2 alloc] initWithFractionNumberArray:tempRow];

NSLog(@"Initial row values: %@", r);

FractionNumber *randomMultiplier = [FractionNumber fractionFromRandomFractionWithMaxNumerator:100 maxDenominator:99 integerChanceIn10:8];

MatrixRow2 *r2= [r rowByMultiplyingByFractionNumber:randomMultiplier];

NSLog(@"%@ * %@ = %@", r, randomMultiplier, r2);

出力は次のとおりです。

2012-04-20 22:33:29.081 RREF[3586:f803] Initial row values: (
    70,
    94,
    98,
    90
)
2012-04-20 22:33:29.083 RREF[3586:f803] (
    770,
    1034,
    1078,
    990
) * 11 = (
    770,
    1034,
    1078,
    990
)

2 番目の出力行では、r の値が乗算された値に変更されています。それは読むべきです:

[70 94 98, 90] * 11 = [770 1034 1078 990]
4

1 に答える 1

2

配列の浅いコピーを行っています。変更する前に、配列内の各項目をコピーする必要があります。

これには、各項目のコピーを作成し、それを新しい配列に追加する (またはコピーした配列内の項目を各項目のコピーで更新する) 必要があります。

不変オブジェクトが動作するものはすべて、不変であるか、変更する前にコピーする必要があります。

于 2012-04-21T02:47:22.370 に答える