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?
You have not created the timer. Declaring a variable is not enough. You do need to create the timer.
And you should destroy it too. Add a destructor to the class
and implement it like this
I would also recommend that you make your
clockfield have private visibility. It’s not good to expose the internals of a class like that.Note that I have included calls to the inherited constructor and destructor. These are not necessary in this class since it derives directly from
TObjectand the constructor and destructor forTObjectis 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.