keysSortedByValueUsingSelector崩溃但sortedArrayUsingSelector运行正常

时间:2012-12-28 02:06:15

标签: iphone objective-c ios xcode nsmutabledictionary

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

我使用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];
}

1 个答案:

答案 0 :(得分:0)

NSMutableDictionary的方法是:

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

这意味着密钥应该实现NSCopying protocol