问题描述
- 排序/过滤一个NSArray / NSMutableArray
-
如果定义了一个类:MyClass ------- NSString *name
然后放到数组里(或者可变数组),然后通过name条件筛选数组:
[NSPredicate predicateWithFormat:@"name = %@", someValue];
或者升序排序数组:
[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
问题:如果是一个string数组(或者是NSNumber),能不能用相同的格式?
例如数组:
@[@"Cat", @"Bat", @"Dog", @"Cow"];
能不能用
predicateWithFormat
或者sortDescriptorWithKey
来过滤和排序?我知道可以用block。
解决方案
当然可以用predicateWithFormat
过滤string数组和其他类型的数组。排序用sortedArrayUsingSelector
,selector任意(比如,比较可以用caseInsensitiveCompare
)。
在简单数组中没有关键字key,所以不能用sortDescriptorWithKey
。
时间: 2024-09-17 03:55:45