2
\$\begingroup\$

I am currently handling some setup of an object on a background thread (I am using a concurrent queue within the following initWithDocumentFileURL method):

+ (TWReaderDocument *)initWithDocumentFileURL:(NSURL *)url withLoadingCompletionBlock:(loadingCompletionBlock)completionBlock{

 __block NSError *error;
TWReaderDocument * twDoc = [[TWReaderDocument alloc] init];
twDoc.status = ReaderDocCreated;
twDoc.doc = [ReaderDocument withDocumentFilePath:[url path] withURL:url withLoadingCompletionBLock:^(NSError *_error) {

    if (_error)
    {
        _error = error;
        twDoc.status = ReaderDocReady;
    }
    else twDoc.status = ReaderDocFailed;

}];

//completionBlock(error);

return twDoc;
}

Header

@property (nonatomic, assign, readonly) TWReaderDocumentStatus status;

Implementation

- (TWReaderDocumentStatus) status {

    __block TWReaderDocumentStatus readStatus;

    dispatch_sync([ReaderDocument concurrentLoadingQueue], ^{
        readStatus = _status;
    });

    return readStatus;

}

If I would like to access the status property on the main thread do I need to take any precaution or there is nothing to take care of as I am just reading the property on the main thread?

\$\endgroup\$
1
  • \$\begingroup\$ Unrelated, but what is the intent of the line of code that says _error = error? I could imagine error = _error if you were trying to save the NSError passed to your block (but then again, the idea of updating a __block variable from an asynchronous method doesn't make a lot of sense). \$\endgroup\$
    – Rob
    Oct 6, 2014 at 3:34

1 Answer 1

3
\$\begingroup\$

If all you're trying to synchronize is TWReaderDocumentStatus, and if that's a simple data type (e.g. an integer or float, not an object), you can just define it as atomic, and it can be safely read and updated from multiple threads, with no custom getter required. This is one of the very few situations where atomic can be useful for synchronization (and it's remarkably efficient).

By the way, if your property has a public interface that is readonly, make sure the private class extension redefines it as readwrite so the setter is synthesized for you. And make sure that you only set it using the setter (not bypassing it and using the instance variable directly).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.