Objective-C threads and NSZones - objective-c

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.

Related

How to end a polling thread created with detachNewThreadSelector?

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.

Debug thread safety issue on iOS

I've got a thread safety bug somewhere in a fairly large set of code. It's reproducible as a random crash simply by scrolling around in my CATiledLayer for a few seconds in the simulator, and solvable by locking my drawing code into a single thread (which is not ideal, since CATiledLayer is designed to be multi-threaded and my drawing code is slow enough to need it).
How do I go about debugging a thread safety issue? I suspect it's somewhere in my code to lazily fetch (and cache) the data which is being drawn, but that doesn't narrow it down much.
I've skim read the Concurrency Programming Guide, but don't see anything that talks about debugging, it just talks about how to structure your code.
Which concurrency method do you use? GCD or NSThread? And if I can't convince you to use single thread for drawing, try to use #syncronized in your setter/getter methods (or atomic properties, if you use synthesized setters/getters).

Is Objective-C Delegation Really Multithreaded?

My question is very straight forward: is the delegate design pattern in iOS truly multithreaded? Meaning is there actual parallel execution going on or is it still all running on the main thread?
It depends if you call the delegate methods on a different thread or not. In general, delegate methods are called on the same thread after a certain event. In short terms, threading has nothing to do with delegation and from my experience Apple always posts the delegate callbacks methods to the main thread (however, you can choose not to, but things can become nasty if you do).
Delegation has nothing to do with threading. Delegation is about allowing one object to make decisions on behalf of another. It is normally done in a single-threaded manner, since there's little to be gained from spawning a thread every time you want to ask a delegate something and it would complicate the design considerably.

What is the difference between NSNotificationCenter and the Key Value Observing technique?

I just read a couple of tutorials regarding KVO, but I have not yet discovered the reason of its existence. Isn't NSNotificationCenter an easier way to observe objects?
I am new to Stackoverflow, so just tell me if there is something wrong in the way I am asking this question!
Notifications and KVO serve similar functions, but with different trade-offs.
Notifications are easy to understand. KVO is... challenging... to understand (at least to understand how to use it well).
Notifications require modification to the observed code. The observed must explicitly generate every notification it offers. KVO is transparent to the observed code as long as the observed code conforms to KVC (which it should anyway).
Notifications have overhead even if you don't use them. Every time the observed code posts a notification, it must be checked against every observation in the system, even if no one is observing that object (even if no one is observing anything). This can be very non-trivial if there are more than a few hundred observations in the system. It can be a serious problem if there are a few thousand. KVO has zero overhead for any object that is not actually observed.
In general, I discourage KVO because of some specific implementation problems that I believe make it hard to use correctly. It's difficult to observe an object that your superclass also observes without special knowledge of your superclass. Its heavy reliance of string literals make small typos hard to catch at compile time. In general, I find code that relies heavily on it becomes complex and hard to read, and begins to pick up spooky-action-at-a-distance bugs. NSNotification code tends to be more straightforward and you can see what's happening. Random code doesn't just run when you didn't expect it.
All that said, KVO is an important feature and developers need to understand it. More and more low-level objects rely on it because of it's zero-overhead advantages. But for new developers, I typically recommend that they rely more on notification rather than KVO.
There is a third way. You can keep a list of listeners, and send them messages when things change, just like delegate methods. Some people call these "multicast delegates" but "listeners" is more correct here because they don't modify the object's behavior as a delegate does. Doing it this way can be dramatically faster than NSNotification if you need a lot of observation in a system, without adding the complexity of KVO.

nonatomic in multi threaded iOS environment

Most iPhone code examples use the nonatmoc attribute in their properties. Even those that involve [NSThread detachNewThreadSelector:....]. However, is this really an issue if you are not accessing those properties on the separate thread?
If that is the case, how can you be sure nonatomic properties won't be accessed on this different in the future, at which point you may forget those properties are set as nonatomic. This can create difficult bugs.
Besides setting all properties to atomic, which can be impractical in a large app and may introduce new bugs, what is the best approach in this case?
Please note these these questions are specifically for iOS and not Mac in general.
First,know that atomicity by itself does not insure thread safety for your class, it simply generates accessors that will set and get your properties in a thread safe way. This is a subtle distinction. To create thread safe code, you will very likely need to do much more than simply use atomic accessors.
Second, another key point to know is that your accessors can be called from background or foreground threads safely regardless of atomicity. The key here is that they must never be called from two threads simultaneously. Nor can you call the setter from one thread while simultaneously calling the getter from another, etc. How you prevent that simultaneous access depends on what tools you use.
That said, to answer your question, you can't know for sure that your accessors won't be accessed on another thread in the future. This is why thread safety is hard, and a lot of code isn't thread safe. In general, if youre making a framework or library, yeah, you can try to make your code thread safe for the purposes of "defensive programming", or you can leave it non-thread safe. The atomicity of your properties is only a small part of that. Whichever you choose, though, be sure to document it so users of your library don't have to wonder.