Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

iphone - Does NSURLConnection Block the Main/UI Thread

I am downloading images in table view cells as they scroll onto the screen. For UX reasons, I start downloading the images in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath. I do not wait until the table view is done scrolling. When the table view cell is set, I start downloading images that I do not have already. However, they do not seem to fully download until the table view stops moving. As soon as it stops moving, the images almost download instantly.

Is there anyway to use NSURLConnection where it is not blocked by the main UI thread? Or, is there a way where these images will download very quickly while the table view is being scrolled.

** EDIT **

To prove that NSURLConnection is slower I used NSThread to detach a new selector in a different thread. I then download the data and call back to the main thread where I create a UIImage and show it in the table view. This method works MUCH faster.

Personally, I think that NSURLConnection is getting thrown into the event loop where the UITableView scrolling is blocking it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Read NSDefaultRunLoopMode vs NSRunLoopCommonModes for a good explanation of why all the download delegate notifications are queued up, but to download while scrolling when using the main thread change from this:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];

to this:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self
                                                      startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
                      forMode:NSRunLoopCommonModes];
[connection start];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...