Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Defaults to atomic for scalar properties?

A friend told me that the @property default for scalar properties (BOOL, NSInteger, etc.) is nonatomic. I.e.,

@property BOOL followVenmo;

defaults to

@property (nonatomic) BOOL followVenmo;

But, I was always under the impression that the default is always atomic, scalar or not.

Which is it?

like image 527
ma11hew28 Avatar asked Jul 26 '11 22:07

ma11hew28


1 Answers

Be careful with this "scalar" terminology. An NSString * property is also a pointer, exactly like the example you provided with a pointer to BOOL.

From Apple docs: (The Objective-C Programming Language)

If you specify retain or copy and do not specify nonatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value—the implementation will be similar to the following:

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

You can't apply an object-level lock in something that's not an object, so (non)atomic in properties of primitive types has basically no effect.

You can conclude that atomic only applies to object properties, and this is reinforced in the docs:

If you specify nonatomic, a synthesized accessor for an object property simply returns the value directly.

To clarify whether you should specify one or the other: technically, properties without a nonatomic are considered atomic, but remember that it has no meaning for primitive types. Thus, you may want to save some typing and avoid nonatomic in these.

like image 119
sidyll Avatar answered Nov 15 '22 10:11

sidyll