Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
share|improve this question
2  
classes have no global variables – peko 1 hour ago
That are instance variables. See Property vs. instance variable and many others ... – Martin R 1 hour ago

2 Answers

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.
share|improve this answer
A property is not necessarily backed up by an instance variable. – Martin R 1 hour ago

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

share|improve this answer
A property is not necessarily backed up by an instance variable. – Martin R 1 hour ago
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 52 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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