我正在尝试根据字母表在 TableView 中创建部分,并在这些部分下按字母顺序对我的条目进行排序。
我已经在 bandsArrayIndex 中收集了 bandsArray 的每个条目中的第一个字母,现在我正在尝试使用 NSPredicate 来计算每个字母的数量。
我正在通过关注 this guide 来做到这一点.
他们使用的是 NSArray,而我使用的是 NSDictionary,但似乎无法正常工作。谁能帮帮我?
当试图显示其中包含 TableView 的 View 时,应用程序崩溃。 在调试器控制台中显示以下错误:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string
这是我的代码
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *alphabet = [bandsArrayIndex objectAtIndex:section];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
NSArray *letters = [bandsArray filteredArrayUsingPredicate:predicate];
return [letters count];
}
编辑:这是我的 bandsArray。
标题
NSMutableArray *bandsArray;
@property (nonatomic, retain) NSMutableArray* bandsArray;
实现
// set array from plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"Bands" ofType:@"plist"];
NSMutableArray* tmpArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
self.bandsArray = tmpArray;
// sort array after name ascending
NSSortDescriptor *nameSorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
[bandsArray sortUsingDescriptors:[NSArray arrayWithObject:nameSorter]];
最佳答案
你是说 bandsArray
是字典数组吗?如果是这样,并且假设每个字典都有一个 name
键,您应该能够将谓词更改为类似 @"SELF.name beginswith[c] %@"
的内容。
另一方面,如果 bandsArray
实际上是一个字典本身,也许您想执行 [[bandsArray allKeys] filteredArrayUsingPredicate...]
。
关于iphone - NSDictionary 上的 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4901774/