Question:
I have a TXMLDocument component on my form, and I have no problems using it. However, I tried creating a TXMLDocument at
runtime, and with the same exact code that worked earlier, I am getting access violations! What is causing this?
Answer:
Most likely, you are creating TXMLDocument like this:
var
Doc: TXMLDocument;
begin
Doc := TXMLDocument.Create(nil);
end;
The important thing to notice is that you are passing in nil as the owner. What happens then is that TXMLDocument
takes on a different behavior; it acts as a reference counted object that automatically frees itself when those
references reach zero. This means that the next time you do something to Doc that causes a decrease in the reference
count, you run the risk of destroying the object and invalidating your reference. The problem is that so much happens
to TXMLDocument behind the scenes, inside of the VCL, that it is hard to say when exactly the reference count is getting
modified. The easiest way to get around this is to use an interface pointer instead of a TXMLDocument reference, like so:
var
Doc: IXMLDocument;
begin
Doc := TXMLDocument.Create(nil);
end;
This lets you have more complete control over the reference, allowing you to specify when exactly it gets decremented by
setting the reference to nil.
Last Modified: 31-OCT-02