Your TSomeObserverClass
is most likely inheriting from TInterfacedObject
.
When you pass it in Attach
it gets passed as IObserver
and this is where the reference counting kicks in. The RefCount goes to 1 when it gets added to Fobservers
and when you destroy locSomeClass
and with it the Fobservers
list it gets removed again which causes the RefCount to drop to 0. Then the instance behind the IObserver
interface reference is being destroyed.
To show the problem here is the minimal code to reproduce it:
var
obj: TInterfacedObject;
list: TInterfaceList;
begin
o := TInterfacedObject.Create;
try
list := TInterfaceList.Create;
list.Add(o);
list.Free;
finally
FreeAndNil(o);
end;
end;
If you execute this you see the EInvalidError in the FreeAndNil which is caused because the instance was already destroyed by the automatic reference counting implemented in TInterfacedObject
.
As already commented you should not mix object and interface references or inherit from a class that does not implement automatic reference counting.