I have an Objective-C class with the following property:
@property (nonatomic, copy) NSString *myString;
The value that’s assigned to myString comes from a remote server. I download the remote contents in another thread using performSelectorInBackground. Once the data has been downloaded I pass it to a selector on the main thread using performSelectorOnMainThread:withObject:. In this selector I assign the data to myString.
How can I safely check if myString is nil in a selector on the main thread?
So I’d like to just ask if (myString) in some selector on the main thread. However I’m unsure about the threading considerations. Perhaps this is a case where the property should be atomic.
If the main thread is the only thread in the system that accesses
myString, then the property access is effectively single-threaded, and you do not needatomic. If the main thread is the only one doing the writing, but other threads also readmyString, declaring the propertyatomicis a good thing to do. In case of multi-threaded access, make sure that you use immutableNSStringrather than theNSMutableString, because even making your propertyatomicis not going to protect a mutable string from returning incorrect results on reads running concurrently with writes.