Can a TTimer be a Delphi class field?

I started learning Delphi two days ago, but I'm stuck. I broke because nothing will work, so I decided to write here. I wanted to create a class that will have a field with its own TTimer object and which will perform some actions for a certain period of time. Is it possible? Suppose we have this 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 copies, but it does not work properly. When I call the constructor, the program is reset (access violation on the line: clock.interval: = 1000;). I do not know what

Sender:TObject 

but I think this is not a problem. Is it possible to create the class that I want?

+5
source share
1 answer

. . .

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

.

destructor Destroy; override;

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

, clock . .

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;

, . , TObject, TObject . - , . , , .

+12

All Articles