问题已解决,这是我如何修复它以供像我这样的新手参考,
我需要删除空格:
ship.countryOfbuild = [[elements objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
我不得不像这样改变谓词: NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"(countryOfBuild contains[cd] %@) OR (shipBuilder contains[cd] %@) OR (name contains[cd] %@) OR (owner contains[cd] %@)",searchText, searchText, searchText, searchText];
原始问题
我正在使用本教程向我的项目添加搜索栏。我让 tableview 一切正常,但搜索功能使应用程序崩溃。我现在搜索的方式是:
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"SELF contains[cd] %@",
searchText];
searchResults = [searchContent filteredArrayUsingPredicate:resultPredicate];
}
这searchContent
是一个从 .csv 文件中读取的可变数组,如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString* pathToFile = [[NSBundle mainBundle] pathForResource:@"ships" ofType: @"csv"];
NSString *file = [[NSString alloc] initWithContentsOfFile:pathToFile encoding: NSUTF8StringEncoding error:NULL];
NSArray *allLines = [file componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
searchContent = [[NSMutableArray alloc] init];
for (NSString* line in allLines) {
NSArray *elements = [line componentsSeparatedByString:@";"];
CargoShips* ship = [[CargoShips alloc]init];
ship.countryOfbuild = [elements objectAtIndex:0];
ship.shipBuilder = [elements objectAtIndex:1];
ship.hullHashtag = [elements objectAtIndex:2];
ship.name = [elements objectAtIndex:3];
ship.owner = [elements objectAtIndex:4];
ship.shipOperator = [elements objectAtIndex:5];
ship.shipDelivery = [elements objectAtIndex:6];
ship.shipFlag = [elements objectAtIndex:7];
ship.shipClass = [elements objectAtIndex:8];
ship.powerPlant = [elements objectAtIndex:9];
ship.HP = [elements objectAtIndex:10];
ship.speed = [elements objectAtIndex:11];
ship.cargoSystem = [elements objectAtIndex:12];
ship.numberOfTanks = [elements objectAtIndex:13];
ship.size = [elements objectAtIndex:14];
[self.searchContent addObject:ship];
}
我想搜索对象的所有 15 个部分(名称、大小、船级等)
目前,这会因错误而崩溃:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't use in/contains operator with collection <CargoShips: 0x714e1b0> (not a collection)'
CargoShips 是我的 NSObject 类。
如何修复 NSPredicate 以在NSMutableArray
不崩溃的情况下搜索对象?
这是完整的代码,如果这让事情变得更容易http://pastebin.com/sw12GwHK