gpt4 book ai didi

iphone - keysSortedByValueUsingSelector 崩溃但 sortedArrayUsingSelector 运行正常

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:31 25 4
gpt4 key购买 nike

我自己找到了解决方法,但仍在尝试理解问题所在。

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

如果我直接在字典上调用 keysSortedByValueUsingSelector,它就会崩溃。但是,如果我先通过 [dict allKeys] 获取 key ,然后调用 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];
}

最佳答案

NSMutableDictionary 的方法是:

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

这意味着 key 应该实现 NSCopying protocol .

关于iphone - keysSortedByValueUsingSelector 崩溃但 sortedArrayUsingSelector 运行正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com