views:

49

answers:

2

Example: In my main thread (the thread that's just there without doing anything special) I call a selector to be performed in a background thread. So there's a new thread, right? And now, inside this background thread I create a new object which holds image data. Next I use that object and want to keep it around for a while. How would I store a reference to that object so I can release it later? Or will the thread be alive as long as this object exists? How does a thread relate to objects which were created in it? Maybe someone can explain this in clear words :-)

A: 

What language/platform are you using?

dutt
The tags would suggest 'iphone', and the language is objective-c
AlBlue
There's also monotouch for iPhone development, so it's not necessarily Objective-C.
Philippe Leybaert
A: 

Storage location and thread creation are two separate concepts. It doesn't matter which thread created an object in terms of who will finally 'own' it or when it will be released later.

Unfortunately, there's no clear-cut answer to your question, but I'd start by thinking about whether this object is a singleton, or whether it's a cache item that can be purged, or whether it's a result object that you need to pass back to some other selector asynchronously.

If it's a singleton, put it in a static var, and never release it (or, consider doing so in response to a low memory warning)

If it's a cache, then have the cache own the item when it's inserted, so you don't have to worry about it. You might need an autorelease to do this, but be careful when using autorelease and threads since each thread may have its own autorelease pool which gets drained at different times.

If it's an object that you need to pass back to another caller, you want to autorelease it as you return and let the caller pick up the ownership of the item.

AlBlue