The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages - More
> Delphi Programming
|
Doubt about object resources freeing
Discuss Doubt about object resources freeing in the Delphi Programming forum on Dev Shed. Doubt about object resources freeing Delphi Programming forum discussing Delphi related topics including Kylix, C++ Builder, and more. Delphi is a high-performance language, originally based on the PASCAL language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

November 28th, 2012, 05:30 AM
|
|
Contributing User
|
|
Join Date: Oct 2012
Location: São Paulo - Brazil
Posts: 33
Time spent in forums: 6 h 35 m 31 sec
Reputation Power: 1
|
|
|
Doubt about object resources freeing
Suppose the construction below. I'm thinking that the resources allocated by the Create method are freed at the end of the "With" block. Am I right? Or are the mentioned resources free at the end of the "NavigatorDeleteClick" method execution?
The variables "Motivo" and "AutorizouExclusao" are declared public in the "TfrmCadMotivoExclusao" class. I would like to know if there were local variables with the same name it would be possible that the compiler use the local variables values instead of the "TfrmCadMotivoExclusao" values. How can I qualify the "TfrmCadMotivoExclusao" variables case they can become ambiguous.
Is it possible a little explanation about the use of "nil" or "self" in this case?
Greetings from São Paulo - Brazil
Ricardo
Code mentioned above:
procedure TFrmCadTele.NavigatorDeleteClick(Sender: TObject);
var detalhe : string;
begin
With TfrmCadMotivoExclusao.Create(nil) do
begin;
ShowModal;
MotivoExclusao := Motivo;
ConfirmaExclusao := AutorizouExclusao;
end;
detalhe := qryTelecom.FieldByName('CDFILIAL').AsString + '-' +
qryTelecom.FieldByName('NRBEM').AsString + '-' +
qryTelecom.FieldByName('NRINC').AsString;
if ConfirmaExclusao then
begin
GeraLogManutencao(FrmMain.IDSistema,'Excluiu Registro',
detalhe,
MotivoExclusao);
qryTelecom.Edit;
qryTelecom.FieldByName('STATIVO').AsString := 'I';
qryTelecom.Post;
RefreshTree;
end;
Abort; // Anula o delete que se seguiria por força do Navigator
end; // NavigatorDeleteClick
|

November 28th, 2012, 10:14 AM
|
|
Contributing User
|
|
Join Date: Jan 2006
Location: Carlsbad, CA
|
|
Te answer is: never!
You must free it.
Code:
With TfrmCadMotivoExclusao.Create(nil) do
try
finally
free;
end;
|

November 28th, 2012, 11:59 AM
|
|
Contributing User
|
|
Join Date: Sep 2008
Posts: 44
Time spent in forums: 10 h 7 m 32 sec
Reputation Power: 5
|
|
Ricardo, vou dar a minha opinião a respeito do que eu possa ter entendido sobre o seu problema:
-> nil -> so usando quando você tem a certeza de que vai "VOCÊ É QUEM VAI DESTROIR" o objeto (de qualquer maneira e precisão) -> Aqui o "SELF", significará o objeto proprietário (OWNER) do recém objeto criado deve se encarregar de destroí-lo. -> "APPLICATION" ou "OUTRO OBJ JÁ CRIADO", eles se encarregarão de destroi o objeto criado (não muito indicado, somente em caso específicos)
-> Self -> se refere ao OBJETO em questão, por exemplo, quando criando o uma CLASSE, ou, se referindo a um objeto (instância deste) já criado dentro de suas PROCEDURES OU FUNÇÕES.
como em: Self.caption -> se estiver dentro de propriedades da INSTÂNCIA DO OBJETO FORM1 da classe TFORM , seria igual a FORM1.caption.
-> WITH -> somente aconselhável a desenvolvedor com muita experiência, pois, a codificação pode se tornar quase "ilegível" ao longo do código.
-> Alocar recursos -> bom, isto pode ser visto de diversas formas e de acordo com o tipo de recurso que você está pretendendo usar: memória, stream, files, images, objetos em geral, etc...
Forma mais adequada, no caso mais simples:
var
xObj:TForm;
xFrmRetorno:Integer;
try
xObj:= NIL;// confirma que a instância do objeto não se refere a nada por enquanto
try
xObj:= TForm.Create( NIL );
with xObj do begin //muito obscuro o uso de "with"
caption := 'nome do form'; // etc..
xFrmRetorno := ShowModal;
end;
if xFrmRetorno = mrOK then begin
//fazer algo
end;
except //se algo errado
on E:Exception do begin
ShowMessage( e.Message ); // a exceção pode ser consertada mais isso demanda de muito mais código / normalmente, use aqui uma procedure para avaliar o erro
end;
end;
finally
if Assigned( xObj ) then FreeAndNil( xObj ); //se o xObj era = nil, nem é executado o FreeAndNIl()
EXIT;
ShowMessage('Será que vou aparecer na tela ou não?');
end;
--> ABORT -> melhor usá-lo no local certo, pois, ele altera o valor do resultado da EXCEPTION, ou seja, pode ocultar a verdadeira mensagem da exceção ocorrida
EXIT -> pode ter uma função parecida com ABORT, neste caso, pois, "pula" para a linha final que poderá ser executada numa rotina.
--> SEMPRE use variaveis LOCAIS para que seu código seja mais claro e seguro. Variáveis GLOBAIS, são as maiores causadoras de erro de projeto pois você necessita verificá-las sempre que for usá-la para não cometer erros maiores.
--> se você esta usando uma base de dados SQL (como FIrebird, estude sobre STORED PROCEDURES e TRIGGER) são melhores do que usar edits ou formularios segundarios para inserir dados nos historicos das ações do usuário.
--> Para autorizar um usuário a executar determinadas funções na base de dados (inserir, editar, excluir) estude sobre RULES (REGRAS) em DB como o Firebird.
--> Mais importante, os Database usam SEMPRE trabalhar dentro um "TRANSAÇÃO", então estude sobre o assunto.
1 -> Insert/Edit, 2-POST/CANCEL, 3-COMMIT/ROLLBACK (COMMITRETAIN/ROLLBACKRETAIN -> somente para experientes) (CURSORS -> para mais experientes ainda heheh)
Para maiores detalhes e uma aula mais adequada, consulte o help online sobre tais questões levantas aqui.
--- Paraná, Brasil il il il
Last edited by emailx45 : November 28th, 2012 at 12:11 PM.
|

November 29th, 2012, 05:17 AM
|
|
Contributing User
|
|
Join Date: Oct 2012
Location: São Paulo - Brazil
Posts: 33
Time spent in forums: 6 h 35 m 31 sec
Reputation Power: 1
|
|
|
Your explanation helps me solve the problem.
Thanks a lot
Ricardo
|

November 29th, 2012, 02:12 PM
|
|
Contributing User
|
|
Join Date: Sep 2008
Posts: 44
Time spent in forums: 10 h 7 m 32 sec
Reputation Power: 5
|
|
Quote: | Originally Posted by nightrider43 Your explanation helps me solve the problem.
Thanks a lot
Ricardo |
Poderia ter respondido em POrtugue Brasileiro mesmo ehheehe
|

November 30th, 2012, 12:37 PM
|
|
Contributing User
|
|
Join Date: Oct 2012
Location: São Paulo - Brazil
Posts: 33
Time spent in forums: 6 h 35 m 31 sec
Reputation Power: 1
|
|
|
This is an english forum. I'm trying to respect the majority here.
If I answered in portuguese the guys here won't understand.
Cheers
Ricardo
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|