0

I am trying to learn objective-c but what is confusing to me is the amount of places one can seem to declare variables. Take for example the SpriteKit example where they implement the GameScene like so:

@implementation GameScene {
    SKShapeNode *_spinnyNode;
    SKLabelNode *_label;
}

I did find this StackOverflow page on that technique however I see no reason why those two variables are specific to the class rather than specific to a GameScene object. I am also confused on why the variable name starts with "_" which is unusual.

Why did they declare these variables like this?

From my understanding I can declare variables within a class with the following methods:

  1. @property within the interface (Can not have a starting value)
  2. Variable within the implementation but not in a bracket
  3. Variable within the the brackets after the (Can not have a starting value)
  4. @synthesise (Shown at the bottom)

There may be additional ones I have not discovered yet

I suppose my question is what is the difference between these three different ways to declare variables within classes (not inside of there methods)?

Also how can you give properties and variables within the brackets initial values since you cant do so with = 0;.

For reference here is the piece of code that uses the @synthesise technique

@interface Box:NSObject
{
    double length;   // Length of a box
    double breadth;  // Breadth of a box
    double height;   // Height of a box
}
@property(nonatomic, readwrite) double height; // Property

-(double) volume;

@end

@implementation Box

@synthesize height; 

I cant figure out how height is declared as a property and in the top brackets and I am not sure why the synthesize part is their either.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
J.Doe
  • 1,502
  • 13
  • 47
  • synthesize is to autocreate getter and setter for the property. the ones in bracket is a simple variable with no getter/setter. – GeneCode Nov 09 '17 at 00:16
  • To give property an initial value, you can set it up in viewdidload or other init method of the class. – GeneCode Nov 09 '17 at 00:18
  • You need to understand the difference between properties and instance variables (ivars) in Objective-C. And find a modern tutorial. The use of `@synthesize` is very outdated. All of your questions have been discussed many times. Search on each individual question. – rmaddy Nov 09 '17 at 00:35
  • Where to put instance variables: https://stackoverflow.com/questions/13566862/where-to-put-ivars-in-modern-objective-c – rmaddy Nov 09 '17 at 00:36
  • Underscores: https://stackoverflow.com/questions/3521254/prefixing-property-names-with-an-underscore-in-objective-c – rmaddy Nov 09 '17 at 00:39

0 Answers0