I’m trying to make an immutable class. Without further ado:
#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
And the tester code:
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);
And the output is:
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
)
In the second output line, the value of r has changed to the multiplied value. It should read:
[70 94 98, 90] * 11 = [770 1034 1078 990]
You’re doing a shallow copy of the array. You need to copy each item in the array before you mutate it.
This will involve creating a copy of each item and adding it to a new array (or updating the items in the copied array with copies of each item).
Everything that an immutable object works with either needs to be immutable or copied before mutating.