iphone - NSDictionary 上的 NSPredicate

标签 iphone objective-c nsdictionary nspredicate

我正在尝试根据字母表在 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/

相关文章:

iphone - 什么是原子存储类型?

iphone - 如何调用在同一个 ViewController 中声明的简单方法?

ios - UICollectionViewCell 将数据发送到另一个 viewController

ios - 从NSDate获取到最后UTC午夜的时间间隔

ios - NSMutableDictionary isKindOfClass NSDictionary 为 false

ios - 未调用自定义委托(delegate)方法

ios - 以编程方式获取 UIKeyboard 背景颜色

ios - 如果应用程序在后台时调用 startUpdatingLocation,CLLocation 管理器不会更新位置

ios - 无法为不同的字典设置不同的值

xcode - 在 Swift 中从数组填充 NSTableView(没有 XCode)