3

我自己找到了一种解决方法,但仍然试图理解这个问题。

我使用 uitableview 创建了一个自动完成文本字段,在编辑文本字段之前它是隐藏的。UI 部分工作正常。问题在于搜索结果部分。我声明了一个本地 NSMutableDictionary 来存储我的结果,因为我希望结果按键的值排序。

如果我直接在字典上调用 keysSortedByValueUsingSelector,它会崩溃。但是,如果我首先通过 [dict allKeys] 获取密钥,然后调用 sortedArrayUsingSelector,它可以正常工作:

// This commented out line will crash
//    NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:)];

    // The next two lines runs fine.
        NSArray *keyArray = [dict allKeys];
        NSArray *sortedKeysArray = [keyArray sortedArrayUsingSelector:@selector(compare:)];

以下是搜索方法的完整源代码:

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
    // Put anything that starts with this substring into the autocompleteUrls array
    // The items in this array is what will show up in the table view
    [autocomplete_symbol_array removeAllObjects];
    rRSIAppDelegate *appDelegate = (rRSIAppDelegate *)([[UIApplication sharedApplication]    delegate]);
    NSString *input_str = [substring uppercaseString];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    int i = 0;
    for(SymbolInfo *symbol_info in appDelegate.m_symbol_info_array)
    {
        i++;
        NSString *info_str = [[[symbol_info.m_symbol uppercaseString] stringByAppendingString:@"|"] stringByAppendingString:[symbol_info.m_company_name uppercaseString]];
        NSUInteger pos = [info_str rangeOfString:input_str].location;
        if (pos != NSNotFound)
        {
            int tmp = pos * 10000 + i;
            NSNumber *map_key = [[NSNumber alloc] initWithInt:tmp];
            [dict setObject:symbol_info forKey:map_key];
        }
    }

// This commented out line will crash
//    NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:)];

// The next two lines runs fine.
    NSArray *keyArray = [dict allKeys];
    NSArray *sortedKeysArray = [keyArray sortedArrayUsingSelector:@selector(compare:)];

    for (NSNumber *key in sortedKeysArray)
    {
        SymbolInfo *symbol_info = [dict objectForKey:key];
        [autocomplete_symbol_array addObject:symbol_info];
    }

//    NSLog(@"everything added: %d", [autocomplete_symbol_array count]);
    [autocompleteTableView reloadData];
}
4

1 回答 1

0

NSMutableDictionary 的方法是:

- (void)setObject:(id)anObject forKey:(id < NSCopying >)aKey;

这意味着密钥应该实现NSCopying 协议

于 2012-12-28T02:34:29.930 回答