AFNetworking/AFNetworking — pull request #2384 by mm-jkolb (2014-10-23 22:58:43+00:00)
Title: Proposed fix for https://github.com/AFNetworking/AFNetworking/issues/1477

The crash appears to be caused by a network thread changing the NSURLSessionTask state property at the same time that the AFNetworking code is attempting to call removeObserver:context: on the same task from a different thread. To help prevent different threads from racing, the observer removal has been moved inside of the observe callback so that it runs on the same thread that is changing the state. Doing this fixes the original problem but uncovers another, NSURLSession sometimes sets the task to completed more than once (seemingly randomly) from different threads. To address this each thread must synchronize on the task so that only one at a time can perform the removal of the observer. This leads to the last issue, calling removeObserver:context: more than once on the same object triggers an exception. To prevent this, the removal is surrounded with a @try/@catch block that ignores the exception. Other ways of making sure the removal of the observer is done only once may be possible, but the added complexity and risk of breaking already complex muti-threaded code made the @try/@catch block seem the safest implementation.