【发布时间】:2010-12-04 16:40:20
【问题描述】:
我是从 Java 背景开始接触 Objective-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];
【问题讨论】:
标签: iphone objective-c memory-management