Friday, December 13, 2013

Asynchronous URLLoading questions about code

Beginners, watching the official tutorial to do, success is a success. But a bit of doubt, please advise the god.
The official tutorial code:
 
- (Void) doProcess {
NSString * urlString = @ "https://api.weibo.com/2/statuses/public_timeline.json";
NSURL * url = [[NSURL alloc] initWithString: urlString];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
[Request setURL: url];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest: request delegate: self];
if (connection)
{
receiveData = [[NSMutableData data] retain];
NSLog (@ "intial done!");
}
else
{
NSLog (@ "sorry");
}
}

Question 1:
[[NSURLConnection alloc] initWithRequest: request delegate: self]; After the execution of this sentence should be executed automatically open a new thread httprequest and other operations, and the main thread here should be executed in parallel. The function is assumed doProcess main thread, then the if (connection) start another thread has access to the network and download the data. The delegate has on receiveData operation. So at this time will not appear likely in the case of receiveData or nil thread was used to download it?

Question 2:
Why receiveData = [[NSMutableData data] retain]; rather than receiveData = [[NSMutableData alloc] init]; do?
Reply:
Issue 1
With a multi-threaded operating data, see you have to do to protect
thread
Issue 2

Class method can directly take data NSMutableData need only retain plus 1, to ensure the proper recovery time, and every time the words alloc expensive ah
Reply:
1.receiveData is after you initialize the request connection request, and the delegate recv operation is after you receive res, obviously both have significant sequence, there can be nil possible.
2.receiveData initialization, receiveData = [[NSMutableData data] retain] is a static method, the system will automatically recycle, and alloc it is manually released. alloc effects and retain the results, in fact, is about the same, retaincount same. As ls to say, expensive, receiveData only be created once, may not have a lot of overhead. I feel.
Reply:
Code seems to have a problem

No comments:

Post a Comment