Search code examples
iosobjective-cmpmediaitem

Why does MPMediaEntity / MPMediaItem use valueForProperty?


The docs for MPMediaEntity (and therefor MPMediaItem) explain that to access properties, you must use valueForProperty: and then it defines a list of keys that will return properties. I'm curious as to why this metadata has to be queried in this way. Why doesn't MPMediaEntity simply expose object properties or getters?

Example:

NSString* title = (NSString*)[item valueForProperty:MPMediaItemPropertyTitle];

Why not something like:

NSString* title = item.title

Solution

  • This pattern is used in a few cases in addition to MPMediaEntity. An example includes NSURL (using getResourceValue:forKey:error:.

    The most likely reason for this pattern is because there are so many possible values and new values can appear over time. The interface is cleaner by having one method (and a growing list of keys). Otherwise the class would have dozens of properties and the class interface would change every time a new value is added.

    It also makes it easier to implement some of the other methods like enumerateValuesForProperties:usingBlock: and canFilterByProperty: because you simply provide keys representing the values. If the class had plain old properties for each value, implementing such methods would be much more difficult.