1

In this SO post, the chosen answer uses the syntax below to get a list of frequentFlyerNumbers from a list of passengers this way.

NSArray *frequentFlyerNumbers = someFlight.passengers.frequentFlyerNumbers;

How is this possible given that passengers is an array and compiler can't infer the type that goes into the array?

I got the following error when implementing passengers.

Property 'frequentFlyerNumbers' not found on object of type 'NSMutableArray *'

Community
  • 1
  • 1
Boon
  • 40,656
  • 60
  • 209
  • 315

1 Answers1

2

The answer you cite is poorly written. The code as presented there won't work.

Dot-syntax, in plain code, is just shorthand for an accessor: someFlight.passengers means [someFlight passengers], which from the context appears to return a NSMutableArray. NSMutableArray of course doesn't have a frequentFlyerNumbers property itself.

To get the effect you want, do something like this:

NSArray *frequentFlyerNumbers = [someFlight valueForKeyPath:@"passengers.frequentFlyerNumbers"];

This will work, and return an array of frequentFlyerNumbers. When there's an array or set along a key path, it "projects" the subsequent path across all members of that array or set, producing an array or set of the results.

rgeorge
  • 7,385
  • 2
  • 31
  • 41