1

我目前有一个可用的 TableView 应用程序,它带有一个后端 sqlite 数据库来提供数据。第一个视图返回静态标题为“States”的所有状态。我想将其更改为按字母顺序返回各州(例如,阿拉巴马州、阿拉斯加州、亚利桑那州、阿肯色州将属于“A”部分——加利福尼亚、科罗拉多州、康涅狄格州将属于“C”部分等) .

我的 appdelegate 调用一个查询来“从状态中选择 id,状态”。我有我认为可以工作的代码来创建下面的部分(我已经通过创建一个只有状态作为对象的 NSMutableArray 对此进行了测试,它工作正常)。

stateIndex = [[NSMutableArray alloc] init];

for (int i=0; i<[listOfStates count]-1; i++){
    //---get the first char of each state---
    char alphabet = [[listOfStates objectAtIndex:i] characterAtIndex:0];
    NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];

    //---add each letter to the index array---
    if (![stateIndex containsObject:uniChar])
    {            
        [stateIndex addObject:uniChar];
    }        
}

没有警告/错误,我运行模拟器但它崩溃了。过了一会儿,我才明白为什么它会崩溃。我试图在搜索过程中查找字母字符,但由于原始查询同时调用 id 和状态名称,它正在查看 id 并失败。搜索中需要 id,因为它链接到另一个表,该表根据所选州加载城市。id 是主键。

所以,我的问题是......有没有办法在这个搜索过程中剥离或跳过 id 字段以创建字母部分?

先感谢您!

更新 SchoolHouse.h ========

#import <UIKit/UIKit.h>
#import <sqlite3.h>

@interface SchoolHouse : NSObject {

}

@property (assign, nonatomic, readonly) NSInteger schoolHouseID;
@property (copy, nonatomic) NSString *schoolHouseName;


-(id) initWithSchoolHouseData:(NSInteger)pk schoolHouseName:(NSString *)name;

@end
4

1 回答 1

0

请参阅下面的新代码。

我猜它崩溃的原因是因为可变数组中的某些字符串长度为零(@""),并且您无法从空字符串中获取第一个字母。我已经添加了一张支票来停止迎合这个。您的for循环条件也将跳过最后一个元素,所以我已经解决了这个问题。另外,我强制第一个字母为大写,所以@"New York"两者@"nevada"都下降@"N"(只是为了使代码更健壮。如果这仍然不适合你,请告诉我:

编辑为使用一组SchoolHouse对象。

在文件的顶部,确保您有:

#include "SchoolHouse.h"

然后将您拥有的代码替换为:

NSMutableArray *stateIndex = [[NSMutableArray alloc] init];

for (int i=0; i < [listOfStates count]; i++) {
    SchoolHouse *schoolHouse = [listOfStates objectAtIndex:i];

    //---skip the object if it's the wrong class---
    if (![schoolHouse isKindOfClass:[SchoolHouse class]]) continue;

    //---skip the object if it's name is empty---
    if (schoolHouse.schoolHouseName.length == 0) continue;

    //---get the first char of the name---
    unichar firstChar = [schoolHouse.schoolHouseName characterAtIndex:0];
    NSString *charString = [[NSString stringWithCharacters:&firstChar length:1] uppercaseString];

    //---add each letter to the index array---
    if (![stateIndex containsObject:charString]) {
        [stateIndex addObject:charString];
    }
}
于 2012-08-31T06:38:31.660 回答