Objective C:SetNeedsDisplay

时间:2011-01-22 01:56:45

标签: objective-c timer

我一直在读这本关于游戏编程的书,但实例并不是那么好。我正在研究一个调用[self setNeedsDisplay]但会导致应用崩溃的应用程序。

这是我所有的代码,从书中逐字复制:

-(void)awakeFromNib {
//start timer that will fire every second
[car setAlpha:0];
[road setAlpha:0];
currentImage = [UIImage imageNamed:@"road.png"];

//start timer that fires every second
[NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

//start timer that fires every hundreth of a second
[NSTimer scheduledTimerWithTimeInterval:(0.01) target:self selector:@selector(onTimerRoad) userInfo:nil repeats:YES];
}

-(void)onTimerRoad
{   
    int tileIndex;
tileIndex += 1;
[self setNeedsDisplay];
}

-(void)onTimer {
[self update];
[self draw];
}

-(void)update {
[self updateRoad];
}

-(void)updateRoad {
[self randomRoadUpdate];
}

-(void)randomRoadUpdate {
int distance = (random() % 11) -5;
CGPoint oldPosition = road.center;
if (oldPosition.x + distance < 96 || oldPosition.x + distance > 224)
    return;
road.center = CGPointMake(oldPosition.x + distance, oldPosition.y);
}

-(void)draw {

}

- (id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
    //init code
}
return self;
}

-(void)drawRect:(CGRect)rect {
CGImageRef image = CGImageRetain(currentImage.CGImage);
CGRect imageRect;
imageRect.origin = CGPointMake(160, 240);
imageRect.size = CGSizeMake(320.0, 480.0);
CGContextRef uiContext = UIGraphicsGetCurrentContext();
CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));
CGContextDrawTiledImage(uiContext, imageRect, image);

}

1 个答案:

答案 0 :(得分:0)

结果而不是[self setNeedsDisplay]我需要做[self.view setNeedsDisplay]