1

hi i don't understand this code of course CS193p

[[PlayingCard rankStrings][self.rank] stringByAppendingString:self.suit];

where rankString is variable method

 + (NSArray *)rankStrings
{
    return @[@"?", @"A", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"J",      @"Q", @"K"];
}

self.rank is a getter of random number

@property (nonatomic) NSUInteger rank;

and self.suit in another variable method

 + (NSArray *)validSuits
{
    return @[@"♥️", @"♦️", @"♠️", @"♣️"];
}

I insert in my code NSLog to understand the functioning .... I understand that it takes rank from the rankStrings and concatenates them with the suit .... but I don't understand how! the method appendingString is clear ... but how do you get the values rank ​​from an rankStrings? the [PlayingCard rankStrings] is simple call to a method of variable and NSUInteger rank is a getter

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • 1
    You're right -- it is confusing, since `[]` is sort of "overloaded". `[self.rank]` is actually an indexing operation on the array returned from the method call `[PlayingCard rankStrings]`. – Hot Licks Jul 21 '14 at 22:10
  • And, of course, `.` here is used to imply a method call to the "getter" for `rank`, not a reference to a field in the structure identified by `self` as would be the case for vanilla C/C++. – Hot Licks Jul 21 '14 at 22:14

2 Answers2

1

The 1st line of code you posted is shorthand for the following:

[[[PlayingCard rankStrings] objectAtIndex:self.rank] stringByAppendingString:self.suit];

Break it down:

NSArray *array = [PlayingCar rankString];
NSString *str = array[self.rank]; // modern syntax for [array objectAtIndex:self.rank]
[str stringByAppendingString:self.suit];

And of course self.rank is the property syntax that is actually converted to [self rank] to call the getter method.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

[PlayingCard rankString] presumably, returns an array.

self.rank is providing an NSUInteger.

We can use the square-bracket notation to access an array index as such:

myArray[10] // this accesses the object at index 10 of myArray

[PlayingCard rankString][self.rank] is accessing the object at the self.rank index of the array returned by [PlayingCard rankString].

The object at that index is presumably a mutable string, so we're now calling a string method on the returned object.

The code snippet you provided could easily be rewritten as such:

NSArray *playingCardArray = [PlayingCard rankString];

NSMutableString *rankString = playingCardArray[self.rank];

[rankString stringByAppendingString:self.suit];
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • To really do it right replace indexing with `objectAtIndex` and replace the dotted property references with `[]` references. – Hot Licks Jul 21 '14 at 22:16