Atomicity: you have likely seen “nonatomic” in property declarations numerous times. When you declare a property as atomic, you usually wrap it in a @synchronized block to make it thread safe. Of course, this approach does add some extra overhead. To give you an idea, here is a rough implementation of an atomic property:
// If you declare a property as atomic ...
// ... a rough implementation that the system generates automatically,
// looks like this:
@synchronized (self) {
return [[myString retain] autorelease];
}
} |
In this code, “retain” and “autorelease” calls are used as the returned value is being accessed from multiple threads, and you do not want the object to get deallocated between calls.
Therefore, you retain the value first, and then put it in an autorelease pool. You can read more in Apple’s documentation about Thread Safety. This is worth knowing, if only for the reason that most iOS programmers never bother to find this out. Protip: this makes a great job interview question! :]
Most of the UIKit properties are not thread-safe. To find out whether a class is thread-safe or not, take a look at the API documentation. If the API documentation does not say anything about thread-safety, then you should assume that the class is not thread-safe.
As a general rule, if you are executing on a secondary thread and you must do something to a UIKit object, use performSelectorOnMainThread.
0 comments:
Post a Comment