NSPredicate忽略字符串中的数字[拼音]

时间:2014-02-18 11:34:05

标签: ios nsstring numbers nspredicate

我看了很多,但一直找不到这个答案......

我的应用中有一个类,其中包含中文拼音发音设置为 发音#[space]发音# 例如你好 [你好]会 ni3 hao3

所以我的问题是如何在搜索过程中让NSPredicate忽略字符串/类中的数字?

理想情况下我可以搜索: “你好” “ ni hao ” 等

并且最终仍然得到相同的结果(你好ni3 hao3

我尝试了一些 LIKE 实例,但每次都失败了......

由于

这是我的数组,根据要求:

     -(NSMutableArray *) wordList{
    cdh = [[NSMutableArray alloc] initWithCapacity:10];
    @try {
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"cdh.sqlite"];
        BOOL success = [fileMgr fileExistsAtPath:dbPath];
        if(!success)
        {
            NSLog(@"Cannot locate database file '%@'.", dbPath);
        }
        if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
        {
            NSLog(@"An error has occured: %s", sqlite3_errmsg(db));

        }


        const char *sql = "SELECT * FROM MAIN";
        sqlite3_stmt *sqlStatement;
        if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
        {
            NSLog(@"Problem with prepare statement:  %s", sqlite3_errmsg(db));
        }else{

            while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
                Words * word = [[Words alloc] init];
                word.head = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)];
                word.pro = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
                word.def = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
                [cdh addObject:word];
            }
        }
         sqlite3_finalize(sqlStatement);
    }
    @catch (NSException *exception) {
        NSLog(@"Problem with prepare statement:  %s", sqlite3_errmsg(db));
    }
    @finally {
        sqlite3_close(db);
        return cdh;

    }
}

Words.h

#import <Foundation/Foundation.h>
#import "TestViewController.h"

@interface Words : NSObject {
NSString *head;
NSString *pro;
NSString *def;
}

@property(nonatomic, copy) NSString *head;
@property(nonatomic, copy) NSString *pro;
@property(nonatomic, copy) NSString *def;

@end

Words.m

#import "Words.h"

@implementation Words

@synthesize head;
@synthesize pro;
@synthesize def;

- (NSString *)searchableStringValue {
NSCharacterSet *invalidSet = [[NSCharacterSet characterSetWithCharactersInString:@"[]0123456789 "] invertedSet];
NSString *searchString = [[pro componentsSeparatedByCharactersInSet:invalidSet] componentsJoinedByString:@""];
    return searchString;
}

@end

TestViewController.h

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

    @interface TestViewController : UITableViewController {
    NSMutableArray *cdh;
    sqlite3 * db;
}
@property(nonatomic,retain) NSMutableArray *cdh;
@property (nonatomic, strong) NSData *myData;

-(NSMutableArray *) wordList;

@end

TestViewController.m(包括谓词)

    - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
    {
        NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"(head beginswith[c] %@) OR (searchableStringValue beginswith[c] %@)", searchText, searchText];
        searchResults = [cdh filteredArrayUsingPredicate:resultPredicate];
    }

    -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
    {
        [self filterContentForSearchText:searchString
                                   scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                          objectAtIndex:[self.searchDisplayController.searchBar
                                                         selectedScopeButtonIndex]]];

        return YES;
    }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];
    } else {
    return [self.cdh count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
//    int rowCount = indexPath.row;

//    Words *word = [self.cdh objectAtIndex:rowCount];
//    cell.textLabel.text = word.head;
 //   cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", word.pro, word.def];

    // Configure the cell...
    Words *word = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        word = [searchResults objectAtIndex:indexPath.row];
    } else {
        word = [cdh objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = word.head;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", word.pro, word.def];
    return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"ShowWordDetails"]) {
    NSIndexPath *indexPath = nil;
    Words *word = nil;

    if (self.searchDisplayController.active) {
        indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
        word = [searchResults objectAtIndex:indexPath.row];
    } else {
        indexPath = [self.tableView indexPathForSelectedRow];
        word = [cdh objectAtIndex:indexPath.row];
    }

    DetailsViewController *destViewController = segue.destinationViewController;
    destViewController.word = word;
}
}

1 个答案:

答案 0 :(得分:1)

您的字符串包含在Words类中。这为您提供了一个完美的机会来创建其他方法来帮助处理它所拥有的字符串(即,您不需要尝试在谓词中执行所有操作)。

例如,考虑添加一个返回:

的方法
- (NSString *)searchableStringValue

此方法将采用您当前尝试搜索的字符串并对其进行变异以删除括号,数字,空格。这可以通过以下方式轻松实现:

NSCharacterSet *invalidSet = [[NSCharacterSet characterSetWithCharactersInString:@"[]0123456789 "] invertedSet];
NSString *searchString = [[##XXX## componentsSeparatedByCharactersInSet:invalidSet] componentsJoinedByString:@""];

其中## XXX ##是您当前尝试搜索的字符串。

现在,您的谓词应该使用searchableStringValue,而不是您当前尝试搜索的字符串。