Objective-c KVC: Collection Accessor Patterns for To-Many Properties, how can I use this to enhance my code?

后端 未结 3 1704
别那么骄傲
别那么骄傲 2021-01-02 21:20

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 ca

3条回答
  •  猫巷女王i
    2021-01-02 21:50

    There are some cases where it comes in really handy! Here are some self-explanatory examples.

    Suppose you have an array of sales prices for the same item and want to know the average price.

    NSNumber *averagePrice = [salesPrices valueForKeyPath:@"@avg.self"];
    

    If it is more complicated this approach is still surprisingly concise and elegant. Suppose you have a transactions array of dictionaries, each with a key "object" and "price". You want the sales total for apples.

    NSArray *apples = [transactions filteredArrayUsingPredicate:
      [NSPredicate predicateWithFormat:@"object = %@", @"apple"]];
    NSNumber *totalApplesSales = [apples valueForKeyPath:@"@sum.price"];
    

    Please also check out the examples given in the Key Value Coding Programming Guide. They are also very illustrative.

提交回复
热议问题