在介紹集合操作符強(qiáng)大的功能前我們先來(lái)看一下它的格式要求
簡(jiǎn)單的集合操作符
@avg 求均值
@interface People : NSObject
@property (nonatomic, copy) NSString *property;
- (instancetype)initWithProperty:(NSString *)property;
@end
- (void)viewDidLoad {
People *zhanSan = [[People alloc]initWithProperty:@"3.5"];
[array addObject:zhanSan];
People *liSi = [[People alloc]initWithProperty:@"4"];
[array addObject:liSi];
NSNumber *averageMoney = [array valueForKeyPath:@"@avg.property"];//結(jié)果是3.75
}
這里做個(gè)說(shuō)明
Left key path 是可以省略的,一般情況下都省略
這個(gè)例子中的集合操作符是@avg
Right key path這里指定了是property財(cái)產(chǎn)這個(gè)屬性,這一個(gè)是不可以省略的除了當(dāng)使用@count時(shí)
可能有人會(huì)提出疑問(wèn),property不是NSString類(lèi)型的嗎匆帚,怎么會(huì)計(jì)算除了均值呢,這里它會(huì)默認(rèn)轉(zhuǎn)換成double類(lèi)型璃岳,而返回值是NSNumber類(lèi)型的趁冈。
留一個(gè)小練習(xí):計(jì)算出一個(gè)數(shù)組中各元素的均值
@count
NSNumber *count = [array valueForKeyPath:@"@count"];//結(jié)果是2
除此外還有@sum,@max响迂,@min
對(duì)象操作符
@distinctUnionOfObjects
NSArray *data = @[@"1", @"1", @"3"];
NSNumber *count = [data valueForKey:@"@count"];
NSArray *dataAfterOperation = [data valueForKeyPath:@"@distinctUnionOfObjects.self"];//結(jié)果是1考抄,3
這個(gè)操作符會(huì)刪除掉重復(fù)的元素,是不是很方便啊
@unionOfObjects
NSArray *data = @[@"1", @"3", @"1"];
NSNumber *count = [data valueForKey:@"@count"];
NSArray *dataAfterOperation = [data valueForKeyPath:@"@unionOfObjects.self"];//結(jié)果是1蔗彤,3川梅,1
這個(gè)操作不會(huì)去重,如數(shù)組中放了很多個(gè)People然遏,而你只想獲得這些人的名字的時(shí)候就可以用這個(gè)操作符了
數(shù)組和集合操作符
如果數(shù)組中嵌套了數(shù)組應(yīng)該怎么辦呢贫途?
@distinctUnionOfArrays
NSMutableArray *array = [NSMutableArray new];
NSMutableArray *array1 = [NSMutableArray new];
People *zhanSan1 = [[People alloc]initWithProperty:@"3.5"];
People *liSi1 = [[People alloc]initWithProperty:@"4"];
[array1 addObject:zhanSan1];
[array1 addObject:liSi1];
NSMutableArray *array2 = [NSMutableArray new];
People *zhanSan2 = [[People alloc]initWithProperty:@"5"];
People *liSi2 = [[People alloc]initWithProperty:@"4"];
[array2 addObject:zhanSan2];
[array2 addObject:liSi2];
[array addObject:array1];
[array addObject:array2];
NSArray *results= [array valueForKeyPath:@"@distinctUnionOfArrays.property"];//結(jié)果是3.5,4待侵,5
除此之外還有@unionOfArrays,@unionOfArrays,@distinctUnionOfSets
推薦閱讀
KVC Collection Operators