1

I am working on the Stanford iOS course assignment 1. I figured out how to fix this and get it working, but I am not sure why it needs to be done this way.

Can someone explain why this works VS the code that displays a value of NULL.

WORKS:

Card *myCard = [**self.myDeck** drawRandomCard];

DOESN'T WORK:

Card *myCard = [**_myDeck** drawRandomCard];
Kevin
  • 53,822
  • 15
  • 101
  • 132
  • 5
    Short answer: The CS193p course uses lazy instantiation extensively. If you don't use the property accessor and access the instance variable directly it is not instantiated via `alloc / init`. – Robotic Cat Mar 02 '14 at 00:05
  • Yes, I see that when I just do _myDeck, the custom 'getter' method including the line 'if (!_myDeck) _myDeck = [[PlayingCardDeck alloc]init];' never executes in the code. I am just a little confused as to the difference between _myDeck and self.myDeck – jgoldstein924 Mar 02 '14 at 00:08
  • 1
    `_myDeck` is the backing variable (the instance variable) behind `self.myDeck`. If you never assign `[[NSArray alloc] init]` to the myDeck property (or backing variable) then the property will always return `nil`. All new properties / variables start out as `nil` until something is either assigned to them or are `alloc / init`ed. – Robotic Cat Mar 02 '14 at 00:25
  • Is myDeck a property or instance variable? Where are you declaring myDeck and how are you instantiating it? http://stackoverflow.com/questions/719788/property-vs-instance-variable – Ivan Lesko Mar 02 '14 at 03:12
  • To clarify something that @RoboticCat said: “All new properties / variables start out as nil” - this is true for Objective-C objects, and properties that are of primitive types (`int`, `float`, etc.). But primitive stack variables (`int myInt;`) contain garbage values until they are initialized by assigning them some value. – Zev Eisenberg May 23 '14 at 19:00

0 Answers0