Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can TTimer object be a field of a Delphi class?

Tags:

delphi

I started learning Delphi two days ago but I got stuck. I broke down because nothing goes my way so I decided to write here. I wanted to create class that would have a field with its own TTimer object and which will perform some action at some time interval. Is it even possible? Suppose we have such code:

Sth = class
private

public
  clock:TTimer;
  procedure clockTimer(Sender: TObject);
  constructor Create();
end;

constructor Sth.Create()
begin
  clock.interval:=1000;
  clock.OnTimer := clockTimer;
end;

procedure Sth.clockTimer(Sender: TObject);
begin
  //some action on this Sth object at clock.interval time...
end;

My similar code copiles but it doesn't work properly. When I call the constructor the program crashes down (access violation at line: clock.interval:=1000;). I don't know what

Sender:TObject 

does but I think that's not the problem. Is it possible to create such class I want to?

like image 594
xan Avatar asked May 02 '12 12:05

xan


1 Answers

You have not created the timer. Declaring a variable is not enough. You do need to create the timer.

constructor Sth.Create()
begin
  clock := TTimer.Create(nil);
  clock.interval:=1000;
  clock.OnTimer := clockTimer;
end;

And you should destroy it too. Add a destructor to the class

destructor Destroy; override;

and implement it like this

destructor Sth.Destroy;
begin
  clock.Free;
  inherited;
end;

I would also recommend that you make your clock field have private visibility. It's not good to expose the internals of a class like that.

TMyClass = class
private
  FClock: TTimer;
  procedure ClockTimer(Sender: TObject);
public
  constructor Create;
  destructor Destroy; override;
end;
....
constructor TMyClass.Create
begin
  inherited;
  FTimer := TTimer.Create(nil);
  FTimer.Interval := 1000;
  FTimer.OnTimer := ClockTimer;
end;

destructor TMyClass.Destroy;
begin
  FTimer.Free;
  inherited;
end;

Note that I have included calls to the inherited constructor and destructor. These are not necessary in this class since it derives directly from TObject and the constructor and destructor for TObject is empty. But if you change the inheritance at some point, and make your class derive from a different class, then you will need to do this. So, in my view, it is good practise to include these calls always.

like image 138
David Heffernan Avatar answered Oct 14 '22 11:10

David Heffernan