我正在尝试创建一个不可变的类。无需再费周折:
#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
)
在第二个输出行中,r 的值已更改为相乘后的值。它应该是:
[70 94 98, 90] * 11 = [770 1034 1078 990]