Componentes - notification (free)

Top  Previous  Next

//Questão:

//  Quando fiz uma propriedade que vincula a um componente

//  deve-se tomar o cuidado ao remover o componente vinculado pois

//  dá acess violation (dentro o obj inspector)

 

//Exemplo do fonte:

//=================

 

  TComponenteNovo = class(TComponent)

  private

    fLabel1: TLabel;

    procedure SetLabel1(const Value: TLabel);

  published

    property Label1: TLabel read fLabel1 write SetLabel1;

  end;

 

 

  procedure TComponenteNovo.SetLabel1(const Value: TLabel);

  begin

    fLabel1 := Value;

    if Value <> nil then Value.FreeNotification(Self);

  end;

 

//-------------------------------------------------------------------------------------

//Solução:

//  Crie uma rotina para "limpar" o componente ao ser removido:

 

//Exemplo do fonte:

//=================

 

  TComponenteNovo = class(TComponent)

  private

    fLabel1: TLabel;

    procedure SetLabel1(const Value: TLabel);

  protected

    procedure Notification(AComponent: TComponent; Operation: TOperation); override; // Remove os componentes vinculados sem dar ACCESS VIOLATION

  published

    property Label1: TLabel read fLabel1 write SetLabel1;

  end;

 

 

  procedure TComponenteNovo.Notification(AComponent: TComponent; Operation: TOperation);

  begin

    inherited Notification(AComponent, Operation);

    if (Operation = opRemove) then

      if (AComponent = fLabel1) then fLabel1 := nil;

  end;