开发者

What happens to a thread's memory when it is cancelled?

I'm writing code to check if there is a network connection present. In a nutshell, the order of events that I want to occur goes like this:

  1. User requests information from a web service.
  2. A timer starts, and checks every second if a connection exists. If it doesn't, put up a view.
  3. When the information is all received from the web service, the timer in 2 ends.

From what I understand, having the timer run while having the web service load requires a new thread with the timer on it. I understand how to do that and a开发者_如何学Pythonm fine. From what I understand, to end that thread, I call [thread cancel];. How do I take care of memory management from within that thread. There was a timer in there, among other things.

My other thread self terminates, and when it does it releases all it's contents. Is there a way to do that with cancel? Thanks.


You will need to keep anything using UIKit in the main thread since UIKit components are not guaranteed to be thread safe. So, your timer and alert are in your main thread, your network traffic is in the background thread. The background thread is going to communicate with the main thread using one of the performSelectorOnMainThread: variants. You can certainly use a timer in a background thread as long as it communicates with your UI via a similar function and does not try to do the alert itself. In terms of communicating from the main thread to your background threads take a look at the performSelector:onThread methods.

In terms of memory you will create a new autorelease pool in the entry point of the new thread and you will drain that pool at the end of the thread. Within the thread itself you manage memory exactly as you do in a main thread, and when the thread terminates all of its memory is released.

For all the details check out the NSThread docs. Here is Apple's memory management document with notes on Autorelease pools

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜