2

I was looking through a Storyboard tutorial here: http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1

When I noticed that the author created properties with a name and type without creating the member variables in the interface section. It was to my understanding previously that the @property/@synthesize declaration in objective C only created a getter / setter for a member variable of that name and type. I didn't think that the variable was implicitly created with the @property/@synthesize. Is the class member implicitly created? If not how does this code work:

@interface Player : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *game;
@property (nonatomic, assign) int rating;

@end
Manlio
  • 10,768
  • 9
  • 50
  • 79
Nirma
  • 5,640
  • 4
  • 35
  • 47
  • possible duplicate of [Using @property and @synthesize with ivar implicit creation](http://stackoverflow.com/questions/6912188/using-property-and-synthesize-with-ivar-implicit-creation) – jscs Feb 13 '12 at 19:36
  • Short answer: yes, `@synthesize` creates an ivar with the same name as the property. The `@property` declaration by itself does not. This is clearly and explicitly stated [in the docs](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW9). – jscs Feb 13 '12 at 19:37
  • Another duplicate, possibly a bit better: http://stackoverflow.com/questions/3238009/property-declaration-and-automatic-backing-storage-allocation – jscs Feb 14 '12 at 03:51

1 Answers1

3

Yes, it's implicitly created with the @sythesize keyword if an ivar of the specified name doesn't already exist. For example, given the above properies:

@synthesize name; // Creates an instance variable called "name"

Alternatively...

@synthesize name = _name; // Creates an instance variable called "_name"

Which means you no longer need to specify ivars in your class' @interface.

Matt Wilding
  • 20,115
  • 3
  • 67
  • 95
  • 1
    It's not really "implicit" -- creating the ivar is [one of the stated purposes](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW9) of the `@synthesize` keyword. – jscs Feb 13 '12 at 20:12
  • I agree; the docs state it explicitly. Speaking strictly from a code syntax point of view, I would describe the creation as "implicit" with the @synthesize keyword. – Matt Wilding Feb 13 '12 at 20:39
  • Small side note: this only works in the "modern" Objective-C runtime. The modern runtime is used on 64-bit OS X and iOS. 32-bit OS X still requires you to explicitly declare ivars even for @synthesized properties. – Andrew Madsen Feb 13 '12 at 21:41