I was reading :Collection Accessor Patterns for To-Many Properties, but I'm not sure where can I or should I use this.
Can someone please point out some scenarios that I can use Collection Accessor Patterns for To-Many Properties
to make my code better or make my code writing easier?
The collection accessor patterns that you were reading about improve the way key value coding works with collections like NSArray, NSDictionary, etc. If you implement them in your own classes, your classes can be used with KVC just like the standard collection classes. For example, maybe you've got a Flight
class that contains a list of Passenger
. But maybe those passengers aren't stored in an NSArray, but pulled from an database or something. If you implement the following methods:
-countOfPassengers
-passengersAtIndexes:
-getPassengers:range:
then code using your class can use KVC to efficiently access the passenger list. For example, you might get a list of passenger frequent flyer numbers (assuming Passenger
has such a property) like this:
NSArray *frequentFlyerNumbers = someFlight.passengers.frequentFlyerNumbers;
That's pretty handy stuff -- saves you from having to iterate over the collection and collect all those numbers yourself. If you weren't aware that you could do that with the standard collections like NSArray, this might seems surprising, so take a minute to absorb that part first and then consider that by implementing a few simple methods you've done the same thing for your own Flight
class. It's pretty cool that this works even though the storage of the passengers is entirely internal to your class.
Now, the methods above only cover getters, but you can do the same for setters by implementing:
-insertPassengers:atIndexes:
-removePassengersAtIndexes:
-replacePassengersAtIndexes:withPassengers:
Now, again, your code can add and remove passengers from a flight using KVC:
[someFlight replacePassengersAtIndexes:bumpedPassengerIndexes
withPassengers:passengersFromLateConnectingFlight];
There are other KVC accessors that you can implement, too, but I don't think I need to list them all for you since they're right there in the article that you linked. The point is that key value coding is useful stuff that's used in a number of places, and by implementing a small handful of methods you can make your own classes KVC compliant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With