fracB
我想知道为什么当它引用一个不可变Fraction
对象时我仍然被允许更改NSCopyWithZone:
?
#import <Foundation/Foundation.h>
@interface Fraction : NSObject <NSCopying>
@property int numerator, denominator;
-(void) set: (int) n over: (int) d;
-(Fraction *) initWithValues: (int) n over: (int) d;
@end
@implementation Fraction
@synthesize numerator, denominator;
-(Fraction *) initWithValues:(int)n over:(int)d {
self = [super init];
if (self)
[self set:n over:d];
return self;
}
-(void) set: (int) n over:(int)d {
numerator = n;
denominator = d;
}
-(Fraction *) copyWithZone:(NSZone *)zone {
Fraction *copied = [[Fraction allocWithZone: zone] init];
[copied set:numerator over:denominator];
return copied;
}
@end
#import "Fraction.h"
#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
@autoreleasepool {
Fraction *fracA = [[Fraction alloc] initWithValues:5 over:5];
Fraction *fracB = [[Fraction alloc] init];
fracB = [fracA copy];
[fracB set:2 over:2];
NSLog(@"%@", fracB);
}
return 0;
}
2012-08-07 20:01:04.248 prog[1972:707] 2/2