I'm new to Objective C, and am using the Stanford CS193P course for the basics. In the first lecture, according to what I understood from it, anytime I declare a property in the header file, Objective C auto-generates the setter and getter for the property, where the getter name is the same as the property name. The professor also mentioned about the @synthesize keyword, which is used to set something as the instance variable name, like so @synthesize card = _card.
So now, any changes can be made to the property by using _card directly as well.
However, he mentions many times that all this happens behind this scenes and none of this appears to us in the implementation file.
If that's the case, then in the code below:
//
// PlayingCard.h
// CardGame
//
// Created by Manish Giri on 9/19/15.
// Copyright (c) 2015 Manish Giri. All rights reserved.
//
#import "Card.h"
@interface PlayingCard : Card
@property (nonatomic,strong) NSString *suit; //one of club, heart, spade, diamond
@property (nonatomic) NSUInteger rank; //numbers from 0 through 13
@end
//
// PlayingCard.m
// CardGame
//
// Created by Manish Giri on 9/19/15.
// Copyright (c) 2015 Manish Giri. All rights reserved.
//
#import "PlayingCard.h"
@implementation PlayingCard
//@synthesize suit = _suit;
//override the getter method "contents" to return the description- rank&suit of the playing card
-(NSString *) contents {
//return [NSString stringWithFormat:@"%lu %@", (unsigned long)self.rank, self.suit];
//if rank is 0 or not set, return ?
NSArray *rankStrings = @[@"?", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12", @"13"];
return [rankStrings[self.rank] stringByAppendingString:self.suit];
}
-(NSString *) suit {
//return ? if suit is nil or not set
return _suit?_suit:@"?";
}
-(void) setSuit:(NSString *)suit {
//check the suit to be set is valid
if([@[@"♥︎", @"♦︎", @"♠︎", @"♣︎"] containsObject:suit]) {
_suit = suit;
}
}
@end
Why do I get the error:
Use of undeclared identifier _suit. Did you mean suit?
After I got this error, I added the line @synthesize suit = _suit, and the error was fixed, but isn't this done automatically? If not, what's the difference?
The professor, most certainly, did not have the @synthesize line in his code (in the slide) while still using _suit.