NSURLConnection Saving Variable Does not work
I am making an (asynchronous) url request.
In the delegate function connectionDidFinishLoading I assign the response of the server to an instance variable.
I wait a few seconds after I make the request and I am SURE that I have received the response.
I have a button linked to an IBAction which prints out this variable to NSLog, but it is ALWAYS null.
I have no idea what's going on. Does the url request start a new thread and any of the variables saved, aren't accessible in the main thread... or why on earth can I not ever see any of my saved variables.
I can properly use the received data inside the connectionDidFinishLoading, but when I assign this data to instance variables and try to access them ou开发者_如何学编程tside the function they are always null.
TL;DR How on earth do I save the responses or a url request for later use!?!
Thanks in advance.
The problem may be that you are not retaining the memory so it is being automatically freed. The instance variable you are assigning, is it a property with "retain" or "copy" specified? You can also manually call retain on the object itself after you set it:
[myString retain];
Using a property is a better way to manage, example .H:
@interface MyClass: Object {
NSString *myString;
}
@property (nonatomic, retain) NSString *myString;
elsewhere in .M:
@synthesize myString
...
...
self.myString = ...
This ensures the string is not released on you until you want to:
[myString release];
self.myString = NULL;
精彩评论