Search code examples
iphoneobjective-cios5.1

weak pointer to NSData cannot read data using NSURLConnection?


I don't truly understand the difference between weak and strong pointer. It doesn't cause any big problem until now I am following an example in the documentation, making an NSURLRequest and use it in NSURLConnection to received data.

The code is like this:

    //create the request with url
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3000/students.json"]];

    //create the with the request
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];


    if (connection) {
        //create NSData instance to hold data if connection is successfull
        self.receivedData = [[NSMutableData alloc]init];
//        NSLog(@"%@",@"Connection successfully");
    }
    else{
        NSLog(@"%@",@"Connection failed");
    }

SO I append data into receivedData in the body of delegate method.

@property (strong,nonatomic) NSMutableData *receivedData;

//delegate method
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.receivedData appendData:data];
    NSLog(@"%@",@"Receiving Data");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"Succeeded! Received %d bytes of data",[self.receivedData length]);
}

the code I posted above is working:) because I have just fixed it.

My question is - The type of the pointer was original weak. I would always get 0 bytes of data from [self.receivedData length] before I have changed the type of pointer from weak to strong and I don't understand why it can't hold the data.


Solution

  • A weak reference doesn't hold onto its contents. You were telling the receivedData variable to look at the mutable data object you created, but not to hold onto it. So when that if block completed, the data's scope ended and ARC released it; there was nothing else holding onto it so it was deallocated and receivedData was set to nil, because it no longer had anything to point to. [self.receivedData length] returned 0 (technically nil) because self.receivedData was nil. By declaring receivedData strong, you told it to hold onto the object it points to, making sure it stays around until you're done with it.