Assuming that you're detecting failure because that NSLog
prints its "iCloud not available" message, you're setting up a classic race condition here:
- You set the value of
self.ubiquityIdentifier
on a global (non-main) queue. - You test the value
self.ubiquityIdentifier
on the main queue.
The two dispatch_async
calls run on different queues. As a result, there's no guarantee that you're setting the value of self.ubiquityIdentifier
before you test it. It will work sometimes, and fail at others, and not necessarily for any obvious reason. When you get the "iCloud not available" message, it's because the second queue checked the value before you assigned any value.
The fix is to change the dispatch calls so that you can guarantee the order of execution. Two possibilities are:
- Combine these two
dispatch_async
calls so that all of the code happens on the same queue, or - Move the second
dispatch_async
inside the first, so that you don't dispatch back to the main queue until you've set a value forself.ubiquityIdentifier
.