0

I'm not sure when it's the right moment to RELEASE a listener object.

I have a object A that uses NSURLConnection's initWithRequest method to retrieve some URL. initWithRequest requires a delegate to listen after the events of dataReceived... So object A creates an object B and passes it as a delegate for initWithRequest method.

When the data is retrieved from the network a method of object B is called. After object B has completed its work who has the responsability to release object B?!?

TO SUMMARIZE:

object A creates object B and make it listener for some event. The event happens and object B makes its job. After object B has done its job who has the responsability to release it?!?

PLEASE NOTE There are many questions and answers on how to remove Observers in Objective-C. Anyway all of them I found they assumed you are using the KVO pattern.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Giorgio
  • 13,129
  • 12
  • 48
  • 75

2 Answers2

1

Have you tried having object B release itself in the 'done receiving data' method? That would seem to be the end of its useful life. Or, you could maintain a reference to it in object A, and then release it in object A's dealloc method.

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
  • Yes the actually the method 'done receiving data' is the last moment when object B is used so it would be perfect to release it after that! So an object can release itself?!?! I had thought about that but I thought it would cause an error! – Giorgio Oct 18 '10 at 11:27
0

According to the NSURLConnection Reference:

The connection retains delegate. It releases delegate when the connection finishes loading, fails, or is canceled.

NSURLConnection is an exception in this regard - most objects do not retain their delegates.

So, in this case, object A should retain object B if A wants to keep using B, in which case it should release it when done; NSURLConnection will take care of its own use of B.

David Gelhar
  • 27,873
  • 3
  • 67
  • 84
  • The sentence from the reference you quoted helps a lot!! THANKS!! So object A doesn't need to re-use connection and object B. They are used only once to retrieve some data. In this way a solution could be to release the connection object in the end of the method (void)connectionDidFinishLoading:(NSURLConnection *)connection when the connection is release it will cause also the object B to be automatically release since the connection object is the only wants that retains it! Does this make sense?! – Giorgio Oct 18 '10 at 11:48