Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@property for int type?

Just a quick question if I may, I have always (since learning obj-c) written int properties as follows...

@property(nonatomic, assign) int myValue;

I am now thinking that this might be overkill and I might as well write...

@property int myValue;

Just curious, I know that "assign" is the default behaviour and that "nonatomic" can be fractionally faster ...

all the best

Gary

like image 541
fuzzygoat Avatar asked Oct 19 '10 10:10

fuzzygoat


People also ask

What is int property?

An implementation of Property to be used specifically with fields of type int . This type-specific subclass enables performance benefit by allowing calls to a setValue() function that takes the primitive int type and avoids autoboxing and other overhead associated with the Integer class.

What does @property do in Objective C?

@property offers a way to define the information that a class is intended to encapsulate. If you declare an object/variable using @property, then that object/variable will be accessible to other classes importing its class.


2 Answers

@property(nonatomic, assign) int myValue;

is not the same as

@property int myValue;

The default for a property is atomic (there's no explicit keyword atomic). So the second example is an atomic property. For a property of primitive type I don't know if any locking occurs, but probably a memory write barrier will be introduced (i.e. the setter will force the value to be written back to main memory, instead of just to the cache). Thus atomic properties are considerably slower than nonatomic properties. However, as a fraction of the total execution time of the program, they could still represent a very small percentage. You won't know until you profile your code.

like image 171
JeremyP Avatar answered Sep 20 '22 07:09

JeremyP


Well, the question of declaring atomicity is a separate one from whether you explicitly declare attributes that are the default. The former will depend on the nature of your code -- is there likely to be contentious multithread access to the property?

Regarding the latter, it's mostly a matter of style, but in general I think you should err on the side of explicit clarity. Exactly how many seconds of your life does it cost to type those extra few keystrokes?

like image 45
walkytalky Avatar answered Sep 23 '22 07:09

walkytalky