well...i try to keep it as brief as possible
the Timer class:
Code:
#import "Timer.h"
@implementation Timer
- (id)setTime:(float)theTime delegate:(id)theDelegate selector:(SEL)theSelector repeats:(BOOL)doRepeat
{
time = theTime;
delegate = theDelegate;
selector = theSelector;
repeats = doRepeat;
timer = [NSTimer scheduledTimerWithTimeInterval:theTime target:self selector:@selector(runLoop:) userInfo:nil repeats:doRepeat];
return self;
}
- (void)restart
{
timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(runLoop:) userInfo:nil repeats:repeats];
}
- (void)stop
{
[timer invalidate];
}
- (void)runLoop:(NSTimer *)theTimer
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[delegate performSelector:selector];
[pool release];
}
@end
i've got a base class Base.m
Code:
#import "Base.h"
@implementation Base
- (id)init
{
entities = [[NSMutableArray alloc] initWithCapacity:0];
return self;
}
- (id)initInView:(UIView *)theView
{
parentView = theView;
return [self init];
}
- (void)start
{
[self draw];
for(Base *entity in entities) [entity start];
}
- (void)end
{
[timer stop];
for(Base *entity in entities) [entity end];
}
- (void)draw
{
self.drawView.frame = CGRectMake(self.x, self.y, self.width, self.height);
for(Base *entity in entities) [entity draw];
}
- (void)addEntity:(Base *)theEntity
{
[entities addObject:theEntity];
}
- (void)removeEntity:(Base *)theEntity
{
[entities removeObject:theEntity];
[theEntity release];
}
- (void)dealloc
{
for(Base *entity in entities) [self removeEntity:entity];
[entities release];
[super dealloc];
}
@end
and a game class:
Code:
#import "Game.h"
@implementation Game
- (id)init
{
[super init];
hud = [[Hud alloc] initInView:parentView];
[self addEntity:hud];
return self;
}
- (void)start
{
[super start];
timer = [[Timer alloc] setTime:0.01 delegate:self selector:@selector(draw) repeats:YES];
}
- (void)dealloc
{
[timer stop];
[timer release];
[super dealloc];
}
@end
game will alloc the hud class (inherited from base class) and include it into its entities. then, when game is started, it runs the timer, which will call the draw method every 1/100 s.
in the hud class draw method, there are the previously mentioned commands (except for the CGRectMake, which is in the super draw method).
Code:
- (void)draw
{
NSNumber *n = [NSNumber numberWithFloat:self.number];
NSString *num = [NSString alloc];
num = [formatter stringFromNumber:n];
// the rest is unimportant
[super draw];
[num release];
}
i hope that this is comprehensible