0

hi i am developing an iPhone application. I need to make a NSURLConnection from Class B delegated to Class B. In the time to establishing the connection,i navigate back to pervious view, ie Class A. So Class B object got deallocated and i received an error from the NSURLConnection as it was delegated to the Class B. So how shall i establish the connection so that it won't crash even if i have navigated to class A. Do we use GCD or some other different threads to make this work fine without setting a different delegate.

Sugan S
  • 1,782
  • 7
  • 25
  • 47

2 Answers2

0

You have to keep a strong reference to the connection in class B, for example @property (strong, nonatomic) NSURLConnection * connection and then as you get rid of Class B you can call [self.connection cancel];

From Apple's NSURLConnection reference document:

After this method is called, the connection’s delegate no longer receives any messages for the connection. If you want to reattempt the connection, you should create a new connection object.

A good place to put this is in -[UIViewController viewDidDisappear];

jackslash
  • 8,550
  • 45
  • 56
  • i need to keep the connection alive even if i come back to Class A because i need to use the response after the connection complete in Class A – Sugan S Nov 08 '12 at 20:25
  • then class A should manage the connection and class B should use delegation to tell class A when to start it – jackslash Nov 09 '12 at 08:43
0

In your ClassA, you should create a strong property for your instance of ClassB, otherwise, when you go back to ClassA, ClassB is popped off the stack and deallocated. Also, if you want to go to the same instance of CLassB when you push again, your code where you push to ClassB should look something like this (assuming you have a property called classB):

if (! self.classB){
    ClassB self.classB = [[ClassB alloc] init]; 
}
[self.navigationController pushViewController:self.classB];
rdelmar
  • 103,982
  • 12
  • 207
  • 218