Buju Buju - 1 month ago 14
Swift Question

Does `nonatomic` makes sense in a `readonly` declared class property?

Lets say I have the public class method

sharedInstance
which is currently implemented as a getter method:

@interface MyClass

+ (instancetype)sharedInstance;

- (void)doSomething;

@end

@implementation MyClass

+ (instancetype)sharedInstance {
static MyClass *shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [[MyClass alloc] init];
});
return shared;
}

@end


Accessing this method in Swift 3.0 would look like this:
MyClass.shared().doSomething()


So to make it more swifty we should change the class method to a class property (new in Xcode 8. but actually I can't find it in the Apple Docu, only in WWDC 2016 video)

@interface MyClass

@property (class, nonatomic, readonly) MyClass *sharedInstance;

- (void)doSomething;

@end

// implementation stays the same


Now in Swift code:
MyClass.shared.doSomething()


So does
nonatomic/atomic
property modifier (don't know the exact term) even makes sense for a getter method which I implement myself in objc?

Answer

The atomic/nonatomic modifiers have no effect in your case, for multiple reasons.

The main reason is that atomicity keywords affect only generated code (i.e. synthesized accessor methods). When you declare a @property in your interface and then implement it with a method (or method pair) in your implementation, the compiler isn't generating code, so your atomicity keyword is ignored.

There are a few ways to get to this situation, and you're triggering a couple of them:

  • First, you have a class property. The compiler can't synthesize accessors or storage for class properties — which means no code generation, so atomicity doesn't apply.

  • Second, if you have a truly readonly property, you have to implement an accessor method — which means there's no code generation and thus atomicity doesn't apply.

    (Note you can also have instance properties declared as readonly in a public interface and synthesized due to a private readwrite redeclaration in your implementation. In that case, not only does atomicity apply, you have to make the atomicity keywords match between your public and private declarations.)

Because specifying either atomic or nonatomic for this property does nothing either way, you're free to just leave atomicity keywords out of your declaration entirely. (The compiler will assume atomic, but as noted that assumption has no effect.)