0

I'm wondering what the difference between a class's public global variable and a class's property is (Objective-C primarily iOS programming). Only thing I notice is that you have to use pointer notation -> to access a class's global variable rather than a dot.

I've read that changing code from using globals to using properties can be a program breaking change. Is that true and if so, why?

Thanks!

Edit:

Block.h

Public Global Variable (I think?) [Edit: I now understand this is an Instance Variable, thanks]

@interface Block : GameObject {
    @public
   int type;
   SKEmitterNode *particles;}

Property

@property (nonatomic) CGFloat x;
sbjluke
  • 309
  • 5
  • 15
  • 2
    classes have no global variables – peko Jul 11 '13 at 07:49
  • That are instance variables. See [Property vs. instance variable](http://stackoverflow.com/questions/719788/property-vs-instance-variable) and many others ... – Martin R Jul 11 '13 at 07:58

2 Answers2

3

No, this is not a "global variable".

It is called an instance variable.

A property often (but not necessarily) has an associated instance variable, but the modern compilers hide that from you.

The big difference between using an instance variable is, that a property is always accessed through its accessors (in your case setX:(CGFLoat)x?and -(CGFloat)x`.

If you wanted, you could overwrite these accessors and do special handling, say, whenever the variable is accessed.

It is always possible to bypass the accessors by using the instance variable directly. In a case of an auto-synthesized iVar, this would be _x.

Note that the -> is not necessary in either case

below
  • 929
  • 6
  • 26
  • 1
    A property is not necessarily backed up by an instance variable. – Martin R Jul 11 '13 at 08:03
  • Absolutely correct Martin, you are right I need to edit that. Even a readwrite property is not necessarily backed up by an iVar. Where was my mind … – below Jul 11 '13 at 08:16
  • "Note that the -> is not necessary in either case" unless 1) you are accessing an object other than `self`, or 2) there is a local variable with the same name that hides the instance variable – newacct Jul 12 '13 at 18:46
1

Even a class property is backed by a class variable even though it is not global.

But with a property one has additional gatekeepers guarding access to the variable:

  • You can make the property readonly.
  • Finetune memory semantics (copy, assign, etc).
  • By using KVO it is easy to let changes propagate automatically.
zoliton
  • 191
  • 5