0

我有一个计时器,它可以更新程序中的标签,并且每当发生用户交互(例如手指向下或滚动)时,计时器都会暂停。我正在使用此代码修复它并且它可以工作,但它似乎正在重新创建内存分配,导致游戏在几分钟内崩溃。

-(void) timeChangerInitNormal {
    if (running == YES)
        if ( _timerQueue ) return;
    _timerQueue = dispatch_queue_create("timer queue", 0);

    dispatch_async(_timerQueue, ^{

        timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(timeChanger) userInfo:nil repeats:YES];

        while ( [timer isValid] ) {
            [[NSRunLoop currentRunLoop] runUntilDate:[[NSDate date] dateByAddingTimeInterval:5.0]];
        }
    });
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
{
    [self _lockInteraction];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
    [self _unlockInteraction];
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    [self _lockInteraction];    
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale;
{
    [self _unlockInteraction];
}

- (void) _lockInteraction
{
    [self _setControls:_staticViews interacted:NO];
    [self _setControls:_autoLayoutViews interacted:NO];
}

- (void) _unlockInteraction
{
    [self _setControls:_staticViews interacted:YES];
    [self _setControls:_autoLayoutViews interacted:YES];
}

- (void) _setControls:(NSArray *)controls interacted:(BOOL)interacted
{
    for ( UIControl *control in controls ) {
        if ( [control isKindOfClass:[UIControl class]]) {
            control.userInteractionEnabled = interacted;
        }
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    [self _updatePositionForViews:_autoLayoutViews];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self _updatePositionForViews:_autoLayoutViews];
}

- (UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView;
{
    return _mapImageView;
}
4

1 回答 1

1

tl;博士

您只想使用普通计时器。创建后将其添加到事件跟踪模式:

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSEventTrackingRunLoopMode];

这将使它在跟踪事件时触发(触摸滑块、滚动视图……)。

如果您仍然想知道:您创建了一个线程,该线程基本上使 CPU 在 while 循环中忙于旋转,创建自动释放的NSDate对象。由于没有内部自动释放池,因此没有释放日期对象。

但不要试图修复你的旧代码。还有更多的问题。

于 2012-11-27T19:43:58.330 回答