1

以下のコードを実行しようとしていますが、コンソールに「Tick」が書き込まれた後もシミュレーターがロックされ続けます。「Tock」は出力されないので、「NSTimeIntervallapsedTime =[startTimetimeIntervalSinceNow];」という行に関係していると思います。IBactionsはボタンでアクティブになります。timerとstartTimeは、.hでそれぞれNSTimerとNSDateとして定義されています。

誰かが私が間違っていることを教えてもらえますか?

コード:

- (IBAction)startStopwatch:(id)sender
{
    startTime = [NSDate date];
    NSLog(@"%@", startTime);
    timer = [NSTimer scheduledTimerWithTimeInterval:1 //0.02
                                             target:self
                                           selector:@selector(tick:)
                                           userInfo:nil
                                            repeats:YES];
}

- (IBAction)stopStopwatch:(id)sender
{
    [timer invalidate];
    timer = nil;
}

- (void)tick:(NSTimer *)theTimer
{
    NSLog(@"Tick!");
    NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
    NSLog(@"Tock!");
    NSLog(@"Delta: %d", elapsedTime);
}

.hには次のものがあります。

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {

    NSTimer *timer;
    NSDate *startTime;
}


- (IBAction)startStopwatch:(id)sender;
- (IBAction)stopStopwatch:(id)sender;
- (void)tick:(NSTimer *)theTimer;

@property(nonatomic, retain) NSTimer *timer;
@property(nonatomic, retain) NSDate *startTime;

@end
4

2 に答える 2

4

あなたが持っている場所:

startTime = [NSDate date];

必要なもの:

startTime = [[NSDate date] retain];

alloc、new、initなしで作成されたものはすべて、自動解放されます(経験則)。つまり、NSDateを作成し、それをstartTimeに割り当て、自動解放(破棄)してから、完全に解放されたオブジェクトに対してtimeIntervalSinceNowを呼び出そうとしているので、爆発します。

保持を追加すると保持カウントが増加したため、自動リリース後も保持されたままになります。ただし、使い終わったら手動でリリースすることを忘れないでください。

于 2009-10-09T00:38:22.153 に答える
3

@propertyを利用するには、次のようにする必要があります。self.startTime = [NSDate date]

于 2009-10-09T01:31:50.437 に答える