SundayMonday
SundayMonday

Reputation: 19727

Safely checking if a variable is nil in Objective-C

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.

Upvotes: 1

Views: 148

Answers (3)

John Calsbeek
John Calsbeek

Reputation: 36497

Once you're in the method triggered by performSelectorOnMainThread:, your threading considerations are over. If you don't have any accesses to myString except from the main thread, then nothing can race with you, and the obvious if (myString) will work.

If you're using NSURLConnection, though, you are probably overcomplicating it. You can asynchronously perform a network request without involving threads at all.

Upvotes: 1

Sixten Otto
Sixten Otto

Reputation: 14816

If you are both reading and writing the value of that property on the main thread, then there's no concurrency, and you don't need to take any special precautions.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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 need atomic. If the main thread is the only one doing the writing, but other threads also read myString, declaring the property atomic is a good thing to do. In case of multi-threaded access, make sure that you use immutable NSString rather than the NSMutableString, because even making your property atomic is not going to protect a mutable string from returning incorrect results on reads running concurrently with writes.

Upvotes: 4

Related Questions