KVC进阶(三)
前言
这篇文章主要介绍KVC中的Collection Operators
,以及自定义Collection Operators
的思路,虽然官方文档中明确的指出目前不支持自定义
![](https://img.haomeiwen.com/i329694/a4b8377834f52f14.png)
正文
Collection Operators
有3种,分别是:Simple Collection Operators
,Object Operators
,Array and Set Operators
。且操作对象均为数组或集合
![](https://img.haomeiwen.com/i329694/498cc0ca760d7ea3.png)
Simple Collection Operators
@avg
:求均值
@count
:求总数
@max
:求最大值
@min
:求最小值
@sum
:求和
![](https://img.haomeiwen.com/i329694/a16fc42686883cd4.png)
如果操作对象(集合/数组)内是NSNumber
,可以这样写
![](https://img.haomeiwen.com/i329694/771b574ba125d1cb.png)
Object Operators
@unionOfObjects
:返回操作对象内部的所有对象,返回值为数组
@distinctUnionOfObjects
:返回操作对象内部的不同对象,返回值为数组
![](https://img.haomeiwen.com/i329694/4dedc71cd05ee866.png)
Array and Set Operators
@unionOfArrays
:返回操作对象(且操作对象内对象必须是数组/集合)中数组/集合的所有对象,返回值为数组
@distinctUnionOfArrays
:返回操作对象(且操作对象内对象必须是数组/集合)中数组/集合的不同对象,返回值为数组
@distinctUnionOfSets
:返回操作对象(且操作对象内对象必须是数组/集合)中数组/集合的所有对象,返回值为集合
提示:集合无重复元素
![](https://img.haomeiwen.com/i329694/4bc6a1a7aa421b32.png)
![](https://img.haomeiwen.com/i329694/f4dd01a697df3ffb.png)
介绍了这么多,Collection Operators
的强大已经不言而喻了吧,如果可以自定义该有多好(梦想还是要有的,万一实现了呢?)
以NSArray
为例,runtime跑一下
![](https://img.haomeiwen.com/i329694/150ea24a3be220b6.png)
可以看到一堆的方法,接着搜索关键字avg
,count
,max
等上述Collection Operators
经过筛选得到如下结果
_avgForKeyPath:
_countForKeyPath:
_maxForKeyPath:
_minForKeyPath:
_sumForKeyPath:
_unionOfObjectsForKeyPath:
_distinctUnionOfObjectsForKeyPath:
_unionOfArraysForKeyPath:
_distinctUnionOfArraysForKeyPath:
_distinctUnionOfArraysForKeyPath:
猜想:实现_<key>ForKeyPath:
即可自定义Collection Operators
尝试定义一个名为@jack
的Collection Operators
![](https://img.haomeiwen.com/i329694/ca7314f783d90b4e.png)
![](https://img.haomeiwen.com/i329694/28d872b744f0ed21.png)
可见,只要写好实现,完全可以自定义一些比较有用的Collection Operators