2008. december 19., péntek
Create without worrying of destroy a component
Problem/Question/Abstract:
How can I prevent resources leak.
Answer:
Make use of Interface characteristic where when the reference goes out of scope it will free itself.
type
IAutoClean = interface
['{61D9CBA6-B1CE-4297-9319-66CC86CE6922}']
end;
TAutoClean = class(TInterfacedObject, IAutoClean)
private
FObj: TObject;
public
constructor Create(AObj: TObject);
destructor Destroy; override;
end;
implementation
constructor TAutoClean.Create(AObj: TObject);
begin
FObj := AObj;
end;
destructor TAutoClean.Destroy;
begin
FreeAndNil(FObj);
inherited;
end;
Application....
procedure TForm1.Button1Click(Sender: TObject);
var
a: IAutoClean;
//must declare as local variable, so when this procedure finished, it's out of scope
o: TOpenDialog; //any component
begin
o := TOpenDialog.Create(self);
a := TAutoClean.Create(o);
if o.Execute then
ShowMessage(o.FileName);
end;
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése