I need help with TVAlue and IsObject and IsObjectInstance.
I need help with TVAlue and IsObject and IsObjectInstance.
So, I have a Dictionary with. The idea is to store different types of data linked to tags.
I now write
dictionary.add('John', '123);
dictionary.add('John List', myStringList);
When I want to retrieve 'John List' I go this:
newList:=dictionary.Items['John List].AsType;
Now, I want to free the dictionary and before this I iterate the items and free them.
Depending on the use, myStringList may be freed somewhere else in the code. So, I do this:
var
tmpValue: TValue;
tmpObject: TObject;
begin
for tmpValue in dictionary.Values do
if tmpValue.IsObject then
begin
tmpObject:=tmpValue.AsObject;
if Assigned(tmpObject) then
FreeAndNil(tmpObject);
end;
end;
Now, if I don't free myStringList this code works correctly. If the list is Freed (or FreeAndNil) the if IsObject is always performed and, also, the if Assigned.
I have tried with IsObjectInstance (which would make more sense) but I get the same behaviour.
Any ideas what I do wrong with this?
Thanks
So, I have a Dictionary with
I now write
dictionary.add('John', '123);
dictionary.add('John List', myStringList);
When I want to retrieve 'John List' I go this:
newList:=dictionary.Items['John List].AsType
Now, I want to free the dictionary and before this I iterate the items and free them.
Depending on the use, myStringList may be freed somewhere else in the code. So, I do this:
var
tmpValue: TValue;
tmpObject: TObject;
begin
for tmpValue in dictionary.Values do
if tmpValue.IsObject then
begin
tmpObject:=tmpValue.AsObject;
if Assigned(tmpObject) then
FreeAndNil(tmpObject);
end;
end;
Now, if I don't free myStringList this code works correctly. If the list is Freed (or FreeAndNil) the if IsObject is always performed and, also, the if Assigned.
I have tried with IsObjectInstance (which would make more sense) but I get the same behaviour.
Any ideas what I do wrong with this?
Thanks
Nope, you can't detect whether or not a pointer is dangling. Fix the real problem.
ReplyDeleteYou need to store weak references to your objects in the dictionary. Here is a small example how to achieve with Spring4D weak references which are being set to nil when the referenced object is being destroyed.
ReplyDeletehttps://bitbucket.org/snippets/sglienke/88rLaz
Thanks for the tips and Stefan Glienke for the example
ReplyDelete