Delphi Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming Languages - MoreDelphi Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old November 28th, 2012, 05:30 AM
nightrider43 nightrider43 is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Location: São Paulo - Brazil
Posts: 33 nightrider43 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 6 h 35 m 31 sec
Reputation Power: 1
Send a message via ICQ to nightrider43 Send a message via MSN to nightrider43 Send a message via Google Talk to nightrider43 Send a message via Skype to nightrider43
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

Reply With Quote
  #2  
Old November 28th, 2012, 10:14 AM
clivew clivew is offline
Contributing User
Dev Shed Regular (2000 - 2499 posts)
 
Join Date: Jan 2006
Location: Carlsbad, CA
Posts: 2,045 clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level)clivew User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Week 6 Days 2 h 37 m
Reputation Power: 382
Te answer is: never!
You must free it.
Code:
With TfrmCadMotivoExclusao.Create(nil) do
try


finally
   free;
end;

Reply With Quote
  #3  
Old November 28th, 2012, 11:59 AM
emailx45 emailx45 is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2008
Posts: 44 emailx45 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 10 h 7 m 32 sec
Reputation Power: 5
Thumbs up

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.

Reply With Quote
  #4  
Old November 29th, 2012, 05:17 AM
nightrider43 nightrider43 is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Location: São Paulo - Brazil
Posts: 33 nightrider43 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 6 h 35 m 31 sec
Reputation Power: 1
Send a message via ICQ to nightrider43 Send a message via MSN to nightrider43 Send a message via Google Talk to nightrider43 Send a message via Skype to nightrider43
Your explanation helps me solve the problem.

Thanks a lot

Ricardo

Reply With Quote
  #5  
Old November 29th, 2012, 02:12 PM
emailx45 emailx45 is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2008
Posts: 44 emailx45 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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

Reply With Quote
  #6  
Old November 30th, 2012, 12:37 PM
nightrider43 nightrider43 is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Location: São Paulo - Brazil
Posts: 33 nightrider43 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 6 h 35 m 31 sec
Reputation Power: 1
Send a message via ICQ to nightrider43 Send a message via MSN to nightrider43 Send a message via Google Talk to nightrider43 Send a message via Skype to nightrider43
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

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming Languages - MoreDelphi Programming > Doubt about object resources freeing

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap