How to end a polling thread created with detachNewThreadSelector? - objective-c

I'm creating a new thread using detachNewThreadSelector ref with toTarget self.
The purpose of the thread is to poll movements and load images as appropriate - it loops and only quits when an atomic bool is set to true in the main thread - which is set in the objects dealloc.
The problem is caused by this (from the detachNewThreadSelector reference):
The objects aTarget and anArgument are retained during the execution of the detached thread, then released
Which means my object will always have a (minimum) retain count of one - because the thread continuously polls. dealloc is therefore never called.
So my question is: how can I dealloc my object taking into account the existence of the polling thread?
The only idea I have right now is to create a destroyThread function of the object, which sets the end thread bool, which would be called from everywhere I'd expect the object to be destroyed. This seems error-prone, are there better solutions?
Thanks in advance.
Update
I had an idea for another solution - in the thread I detect if the retain count is one - if it's one then I know the thread is keeping the object alive, so I break the loop and dealloc is called. Is this a robust solution?

First, avoid detachNewThreadSelector:. Anything you are thinking of doing with it is almost certainly done better with a dispatch queue or NSOperationQueue. Even if you need to manually create a thread (which is exceedingly rare in modern ObjC), it is better to create explicit NSThread objects and hold onto them rather than using detachNewThreadSelector: which creates a thread you can't interact directly with anymore.
To the specific question, if you create your own threads, then you'll need to set that bool somewhere other than dealloc. That means that some other part of the program needs to tell you to shut down. You can't just be released and automatically clean yourself up using manual threads this way.
EDIT: Never, ever call retainCount. No solution involving retainCount is a good solution. Putting aside the various practical problems with using retainCount in more general cases, in this case it ties you manual reference counting. You should switch to ARC as quickly as possible, and retainCount is illegal in ARC (it should have been illegal before ARC, but they finally had a really good excuse to force the issue). If you can't implement your solution in ARC, it is unlikely a good solution.
Again, the best solution is to use GCD dispatch queues (or operations, which are generally implemented with dispatch queues). It is incredibly more efficient and effective for almost every problem than manual thread management.
If you must use a manual thread for legacy code and need to maintain this kind of auto-destruct, the solution is a helper object that owns the thread. Your object owns the helper object, which has a retain loop with the thread. When your object is deallocated, then it tells the thread to shut down, which breaks the retain loop, and the helper object goes away. This is a standard way of managing retain loops.
See Apple's Migrating Away From Threads for more.

Related

Objective-C threads and NSZones

When I first read about NSZone and what it was, I got really excited about the prospect of using zones to isolate threads' memory spaces such that I could effectively kill a thread and dealloc its zone. But it seems NSZone can't really be used for this purpose after all.
So I'm wondering if there's any way to isolate a thread in Objective-C to a particular block of memory that can be killed and dealloced safely?
Failing that, are there ways to spawn child processes (that surely do have their own memory spaces) in Objective-C, similar to how Chrome does things?
Inter-process communication is a subject that is far too challenging for what you're trying to implement. So long as you're just looking for a representation of some work that you can cancel and deallocate, a subclass of NSThread is perfect. By overriding -main, you can have all the benefits of an NSOperation (not caring exactly which thread work occurs on, abstraction from actual threading, encapsulation, etc.), but in a more concrete and cancelable form.

objective-c: relying on dealloc

Is it a legitimate practice to rely on a deterministic dealloc (ex: for clean-up)?
Since ARC, and even manual reference counting, is inherently deterministic, I was wondering what other people thought about relying on dealloc getting called immediately (relatively, considering autoreleasepool).
In other modern programming languages, like C#, a dispose-like pattern is employed when you need deterministic clean-up. And I would imagine Obj-C with garbage collection encourages this behavior, as well.
So, with that said, an example would be a UIViewController which cancels outstanding operations in dealloc, rather than trying to program around the sometimes frustrating semantics of viewDidDisappear.
Another example would be a stream object that implicitly opens and closes in init and dealloc, respectively, rather than requiring open or close to be called.
Since Apple has deprecated GC, I would imagine that these sorts of patterns won't be broken anytime soon, and they are incredibly handy, though I can't find any documentation on whether this should be encouraged.
You are absolutely correct, you can rely on dealloc being called relatively soon after the last reference is released (manually or though ARC, it does not matter). Unlike GC where the finalizer is called when the system has some free time, or in some cases is never called, dealloc gets called very reliably. Apple allows and even encourages using this pattern by suggesting that we should perform all of our resource clean-up tasks inside dealloc.
This does not mean, however, that you should rely on dealloc exclusively. For example, take a look at the NSStream class: it offers you an explicit close method, letting you force closing the stream at will, without waiting for the call of dealloc to happen. This is a very good pattern to follow in case the resource is very expensive (file handles, semaphores, etc.): the primary mechanism for releasing these resources should be a separate close method. The dealloc method should release the resource as well, but it should also issue a warning, informing your that you missed a call of close.
Regardless of your memory management system, tying expensive resources (e.g. files & sockets, images, views, large memory allocations, etc) to object lifetimes is risky. Even if you're manually retaining & releasing, you might unwittingly retain an object somewhere and forget about it (or otherwise delay its release unnecessarily). ARC makes it even more likely that these things will happen, since it's much less apparent where the retains come from, and when the corresponding releases take effect. And of course GC makes it all completely indefinite.
Generally for expensive and/or limited resources you should try to follow a sole-ownership pattern. Yes, you can still retain/release as normal to prevent premature deallocation, but the dominant owner should be well defined and responsible for clearing out the object when it's done - e.g. calling invalidate, or close, or whatever is appropriate. This makes perfect sense in a lot of the common cases - you generally know when you're done with a file or a socket, for example, so even if they happen to be encapsulated inside some wrapper class, you should just close them explicitly.
In some cases this can also help find bugs that would otherwise remain hidden, or be hard to track down. For example, if your file wrapper class raises an exception when read or write are called after the file is closed, you'll soon catch those cases. Whereas if you didn't close the file when you thought you were done with it, the reads and writes would just happen as usual and you might not notice that your file has unexpected data in it.
You can also use the same principles to break retain cycles.

Should I retain the argument with GCD dispatch_X (or does it retain it)

As far as I remember we had something like performSelectorOnMainThread: (and variants) do retain the objects until the method is finished executing" in Apple's documentation. So can we rely on such behavior in ios6? Cause there isn't any info in the NSObject Class Reference now. The same question in case I prefer using GCD dispatch_async/sync - if I have object created in back thread - should I choose dispatch_sync(dispatch_get_main_queue) to be sure that object won't be released until selector executes.
The thing about the Cocoa memory management system is that you NEVER have to care about this. Memory management is completely local -- you never care about what other functions do. The basic rule is -- the caller guarantees that an object argument is valid when the function is called, and does not guarantee anything else.
If a function somehow stores an object for use later, it MUST (by deduction) retain it somehow, since it does not assume that the object is valid for any longer. Conversely, as a caller of the function, you don't need to think about what a function does or whether it does something asynchronously or not, because you are not guaranteeing to the function that its argument is alive at any point after it's called.
blocks, which GCD dispatch capture their context: In this case this means they retain everything they reference until executed :)

When using autorelease, when is it actually released?

Sometimes I wonder when something gets autoreleased. I added an NSLog in the dealloc of various objects, but I couldn't find anything useful.
When does something release when autorelease is used? Is it unpredictable, or is there some extra thread running? Thanks.
When the "autorelease pool expires".
What this typically means, is when the stack is unwound.
So think of it this way - your app is event driven. You get events sent to it - and they are processed through a series of functions. When each of the functions returns, and the event is done being processed, autorelease will be called.
This means you can count on a object to still be alive when you autorelease it, and return it from a function to it's caller. Don't ever expect it to be around when processing any kind of subsequent event, or when called outside you existing stack frame.
From the iOS documentation
Each thread in a Cocoa application maintains its own stack of NSAutoreleasePool objects. When a thread terminates, it automatically releases all of the autorelease pools associated with itself.

What is the cost of using autorelease in Cocoa?

Most of Apples documentation seems to avoid using autoreleased objects especially when creating gui views, but I want to know what the cost of using autoreleased objects is?
UIScrollView *timeline = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, 320, 34)];
[self addSubview:timeline];
[timeline release];
Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases? Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?
There are two costs:
(Assuming you have an option to avoid autoreleased objects.) You effectively unnecessarily extend the lifetime of your objects. This can mean that your memory footprint grows -- unnecessarily. On a constrained platform, this can mean that your application is terminated if it exceeds a limit. Even if you don't exceed a limit, it may cause your system to start swapping, which is very inefficient.
The additional overhead of finding the current autorelease pool, adding the autoreleased object to it, and then releasing the object at the end (an extra method call). This may not be a large overhead, but it can add up.
Best practice on any platform is to try to avoid autorelease if you can.
To answer the questions:
Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases?
Quite the opposite.
Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?
You should always use retain/release if you can -- in the case of NSString there is typically no need to use stringWithEtc methods as there are initWithEtc equivalents.
See also this question.
I have to disagree with Jim Puls - I think that not using Autorelease makes debugging more difficult, because you are more likely to find yourself accidentally leaking memory. Of course Clang static analyzer can pick up some of these instances, but for me, the slight overhead costs in habitually using autorelease are far overshadowed by my code being less likely to be buggy.
And then, only if I have a tight loop I need to optimize will I start looking at performance. Otherwise this is all just premature optimization, which is generally considered to be a bad thing.
I'm surprised nobody has mentioned this yet. The biggest reason to avoid autoreleased objects when you can has nothing to do with performance. Yes, all of the performance concerns mentioned here are absolutely valid, but the biggest downside to autorelease is that it makes debugging significantly more difficult.
If you have an overreleased object that's never autoreleased, it's trivially easy to track down. If you have a user-reported crash that happens intermittently with a backtrace somewhere south of NSPopAutoreleasePool, good luck...
I generally use autoreleased objects these days because they tend to result in simpler, easier to read code. You declare and initialize them, then let the drop out of scope. Mechanically they exist quite a bit longer, but from the perspective of the person writing the code it is equivalent to a stack declared object in C++ automatically being destructed when the function returns and its frame is destroyed.
While there is an efficiency loss, in most cases it is not significant. The bigger issue is the more extant objects and later memory recovery can lead to a more fragmented address space. If that is an issue it usually is fairly simple to go in and switch to manual retain/release in a few hot methods and improve it.
As others have said, readability trumps performance in nonperformance sensitive code. There are a number of cases where using autoreleased objects leads to more memory fragmentation, but in any case where the object will outlive the pool it will not. In those cases the only price you are paying is finding the cost of finding the correct autorelease pool.
One benefit to using autorelease pools is that they are exception safe without using #try/#finally. Greg Parker ('Mr. Objective-C') has a great post explaining the details of this.
I tend to use autorelease a lot as its less code and makes it more readable, IMO. The downside, as others have pointed out, is that you extend the lifetime of objects, thus temporarily using more memory. In practice, I have yet to find overuse of autorelease to be a significant issue in any Mac app I've written. If high memory usage does seem to be an issue (that isn't caused by a genuine leak), I just add in more autorelease pools (after profiling to show me where I need them). But, in general, this is quite rare. As Mike Ash's post shows (Graham Lee linked to it), autorelease pools have very little overhead and are fast. There's almost zero cost to adding more autorelease pools.
Granted, this is all for Mac apps. In iPhone apps, where memory is more tight, you may want to be conservative in your use of autorelease. But as always, write readable code first, and then optimize later, by measuring where the slow/memory intensive parts are.
The costs are:
The time to locate the current thread's autorelease pool and add the object to it.
The memory occupied by the object until it is released at some later point.
If you want to be very conservative with your memory usage, you should avoid autorelease. However, it is a useful technique that can make code more readable. Obsessively using retain/release falls under the umbrella of "premature optimization."
If you are in Cocoa's main event handling thread (which you are most of the time), the autorelease pool is emptied when control returns to the event handler. If your method is short and doesn't loop over large amounts of data, using autorelease to defer deallocation to the end of the run loop is fine.
The time to be wary of autorelease is when you are in a loop. For example, you are iterating over a user's address book and perhaps loading an image file for each entry. If all of those image objects are autoreleased, they will accumulate in memory until you have visited the entire address book. If the address book is large enough, you may run out of memory. If you release the images as soon as you are done with them, within the loop, your app can recycle the memory.
If you can't avoid autoreleasing inside a loop (it's being done by code you didn't write and can't change), you can also manage an NSAutoreleasePool within the loop yourself if needed.
So, be mindful of using autorelease inside loops (or methods that may be called from loops), but don't avoid it when it can make code more readable.
As I understand it, the main downside to using autorelease is that you don't know when the object will finally be released and destroyed. This could potentially cause your app to use a lot more memory than it needs to if you have a lot of autoreleased objects hanging around but not yet released.
Others have answered whether you should autorelease, but when you must autorelease, drain early and drain often: http://www.mikeash.com/?page=pyblog/autorelease-is-fast.html
I notice the code sample you provided is for the iPhone. Apple specifically recommends avoiding autoreleased objects for iPhone apps. I can't find the specific reasoning, but they were hammering this point at WWDC.
One side note to keep in mind is if you are spawning a new thread, you must setup a new Autorelease pool on that thread before you do anything else. Even if you are not using autorelease objects, chances are that something in the Cocoa APIs is.
Old thread, but chipping on for the benefit of newer readers.
I use autorelease vs retain/release depending on the risk of autorelease bugs specific to an object and the size of the object. If I'm just adding some tiny UIImageViews, or a couple of UILabels to my view, autorelease keeps the code readable and manageable. And when the view is removed and dealloced, these subviews should get released soon enough.
If on the other hand we're talking about a UIWebView (high risk of autorelease bugs), or of course some data that needs to be persistent till the 'death' of the object, retain/release is the way to go.
Honestly, my projects have not gotten that big yet, where the additional 'staying-time' of autoreleased objects would create a memory problem. For complex apps, that concern is legitimate.
In any case, I don't think a one-size-fits-all approach would be right. You use whatever approach - or combination of approaches - is right for the project, keeping all the factors mentioned above in mind.