【问题标题】:Is there some way to store indexes of objects passing a test other than NSIndexSet?除了 NSIndexSet 之外,还有什么方法可以存储通过测试的对象的索引吗?
【发布时间】:2012-07-27 20:46:40
【问题描述】:

我有一个表格和搜索栏。该表是从 SQLite DB 生成的,搜索栏搜索这些对象。我遇到的问题是当我想知道搜索结果的索引是什么时,如果我只是查看搜索结果数组并与我的数据库表行进行比较,它无法解释重复条目(http:// stackoverflow.com/questions/11617247/how-can-i-figure-out-what-uitableviewcell-im-clicking-on-during-a-search),然后我使用indexesOfObjectsPassingTest(http:// stackoverflow.com/questions/11674498/how-can-i-determine-the-index-of-an-object-in-an-nsmutablearray-when-i-search-fo)。

现在的问题是,我得到一个 NSIndexSet 作为我的结果。我希望能够像查询 NSMutableArray 一样查询它,但我知道这是不可能的,所以我正在枚举 IndexSet,这会导致严重的内存问题,因为有超过 5,000 个可能的结果。有一个更好的方法吗?我需要确定哪些项目是搜索结果,然后我要在表中查看哪些特定结果。

//when the user searches, this function is called:
- (void) getGrapeMatches {
    numSearchGrapes=0;
    listOfTheGrapeIDs = [[NSMutableArray alloc] init];
    for (NSString *str in listOfGrapes)
    {
        NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
        if (titleResultsRange.length > 0) {
            [searchResult addObject:str];
            numSearchGrapes++;
        }
    }
    BOOL (^test)(id obj, NSUInteger idx, BOOL *stop);

    test = ^ (id obj, NSUInteger idx, BOOL *stop) {

        if ([searchResult containsObject: obj]) {
            return YES;
        }
        return NO;
    };

    //this is the part that takes forever because I have over 5000 items in listOfGrapes
    NSIndexSet *indexes = [listOfGrapes indexesOfObjectsPassingTest:test];
    NSUInteger index=[indexes firstIndex];
    while(index != NSNotFound)
    {
        NSString *tempString = [NSString stringWithFormat:@"%d",index];
        [listOfTheGrapeIDs addObject:tempString];
        index=[indexes indexGreaterThanIndex: index];
    }
}

我依赖listOfTheGrapeIDs,因为这是我稍后在表格单元格中找出我正在查看的项目的方式。我只是希望有一种更简单的方法来做到这一点。让我知道是否需要更多代码来帮助理解这个问题。

【问题讨论】:

  • 不确定我是否完全理解——但您的数据库不能使用 SQL 查询直接返回感兴趣的结果吗?现在您有了与您的搜索词匹配的对象。
  • 不存储每个索引的字符串化 (?!) 版本,为什么不将 listOfGrapes 过滤为仅通过测试的对象?
  • 好的,现在我想知道为什么我很久以前没有想到使用 SQL 查询。出色且完全明显的解决方案。谢谢!!!
  • @nielsbot,如果您将其发布为答案,我将投票并接受。非常感谢您发布它!

标签: objective-c xcode nsmutablearray xcode4.3 nsindexset


【解决方案1】:

转帖为答案:

不确定我是否完全理解——但您的数据库不能使用 SQL 查询直接返回感兴趣的结果吗?现在您有了与您的搜索词匹配的对象。

【讨论】:

    猜你喜欢
    • 2017-05-09
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多