RAD Studio
ContentsIndex
PreviousUpNext
Creating Properties for Interfaces

You can use an interface as the value of a published property, much as you can use an object. However, the mechanism by which your component receives notifications from the implementation of that interface differs. In Creating properties for subcomponents, the property setter called the FreeNotification method of the component that was assigned as the property value. This allowed the component to update itself when the component that was the value of the property was freed. When the value of the property is an interface, however, you don't have access to the component that implements that interface. As a result, you can't call its FreeNotification method. 

To handle this situation, you can call your component's ReferenceInterface method:

procedure TDemoComponent.SetMyIntfProp(const Value: IMyInterface);
begin
  ReferenceInterface(FIntfField, opRemove);
  FIntfField := Value;
  ReferenceInterface(FIntfField, opInsert);
end;

Calling ReferenceInterface with a specified interface does the same thing as calling another component's FreeNotification method. Thus, after calling ReferenceInterface from the property setter, you can override the Notification method to handle the notifications from the implementor of the interface:

procedure TDemoComponent.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited Notification(AComponent, Operation);
  if (Assigned(MyIntfProp)) and (AComponent.IsImplementorOf(MyInftProp)) then
    MyIntfProp := nil;
end;

Note that the Notification code assigns nil to the MyIntfProp property, not to the private field (FIntfField). This ensures that Notification calls the property setter, which calls ReferenceInterface to remove the notification request that was established when the property value was set previously. All assignments to the interface property must be made through the property setter.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!