开发者

is Accessing ViewController's property thread safe?

Is it okay to do

[BNUtilitiesQuick searchController].searchList.text not in main thread? for example?

I've heardNSString * is threadSafe. However,

what about when I perform

NSString * searchTerm =[BNUtilitiesQuick searchController].searchList.text;

the [BNUtilitiesQuick searchController].searchLi开发者_JS百科st.text change to another string?


You're main concern here in a multithreaded environment is that the objects referenced don't get released while you're attempted to read them.

Assuming you're using custom classes with synthesized properties, as stated in the Objective-C doc on declaring properties, properties are declared atomic by default. The synthesized code will be similar to the following:

[_internal lock]; // lock using an object-level lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;

This, more or less, let's you use the returned object without worry of it being released on you. So, if you don't declare your properties as nonatomic, you should be OK as far as protecting against crashes due to improper memory management.

If these are not custom classes, you may want to check the class's documentation to determine how the properties have been declared.

Data integrity, however, is a different concern. Even if all the properties specified in your line of code are declared atomic, that doesn't guarantee that all threads will see the same values at all times. So, yes, the value of text may change while a thread gets its value the way you've described. The easiest solution is read/write mutable data from the same thread.

And, yes, NSString is generally thread-safe as it is immutable.

You may wish to review Apple's thread programming guide for more information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜