我來自Java背景的Objective-C。我無法理解爲什麼下面的代碼會生成異常。爲什麼目標C中的某些對象成員超出範圍C
@interface Stopwatch : NSObject {
NSDate *start;
int mode;
}
@property(nonatomic,assign) NSDate *start;
@property(nonatomic,assign) int mode;
@end
@implementation Stopwatch
@synthesize start, mode;
-(id) init{
self = [super init];
if(self){
start = [NSDate date];
mode = -1;
}
return self;
}
@end
@interface StopwatchController : NSObject {
Stopwatch *stopwatch;
}
@property (nonatomic,assign) Stopwatch *stopwatch;
- (void) useStopwatch:(Stopwatch*)aStopwatch;
- (void) updateStopwatch;
@end
@implementation StopwatchController
@synthesize stopwatch;
- (void) useStopwatch:(Stopwatch*)aStopwatch{
stopwatch = aStopwatch;
}
- (void) updateStopwatch{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setTimeStyle:NSDateFormatterMediumStyle];
[dateFormat setDateStyle:NSDateFormatterMediumStyle];
NSString *string = [dateFormat stringFromDate:stopwatch.start];
NSLog(@"%@",string);
}
@end
因此,當下面的代碼運行時,我看到stopwatch.start超出範圍,但不是秒錶?
Stopwatch *sw = [[Stopwatch alloc]init];
StopwatchControlelr *swc = [[StopwatchController alloc]init];
[swc useStopwatch:sw];
[swc updateStopwatch];