AutoComplete TableView响应非常慢

时间:2012-11-20 15:54:38

标签: objective-c json uitableview ios5

我正在尝试访问我的网络服务以从那里获取字符串并使用以下方法将其放入我的AutoCompleteTableView -

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSString *substring = [NSString stringWithString:txtSearching.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];

if (([substring isEqualToString:@""]) || (substring == nil) || ([substring length] == 0)){

    autoCompleteTableView.hidden=YES;
}

NSString *jsonUrl = [NSString stringWithFormat:MYAPI,substring];
NSURL *url = [NSURL URLWithString:[jsonUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSArray *data = [jsonData objectFromJSONData];

for (int i = 0; i< [data count]; i++) {

    NSDictionary * dic = [data objectAtIndex:i];
    [elementArray addObject:[dic objectForKey:@"keyword"]];
}  
[self searchAutocompleteEntriesWithSubstring:substring];
[elementArray removeAllObjects];

return YES;
}

而且,我的searchAutocompleteEntriesWithSubstring

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {

// Put anything that starts with this substring into the autoCompleteArray
// The items in this array is what will show up in the table view
//[elementArray removeAllObjects];
[autoCompleteArray removeAllObjects];

 int lengthOfSubstring = [substring length];
for(NSString *curString in elementArray) {
    int lengthOfCurentString = [curString length];
    if (lengthOfCurentString >=lengthOfSubstring) {
        NSString *substringRangeLowerCase = [[curString substringWithRange:NSMakeRange(0,[substring length])] lowercaseString];
        NSString *substringRangeUpperCase = [[curString substringWithRange:NSMakeRange(0,[substring length])] uppercaseString];
        NSString *substringRangeCase = [[curString substringWithRange:NSMakeRange(0,[substring length])] capitalizedString];
        if (([substring isEqualToString:@""]) || (substring == nil) || ([substring length] == 0)) {
      //      NSLog(@"current string = [%@]",curString);
        }else{
            if (([substring isEqualToString:substringRangeLowerCase]) || ([substring isEqualToString:substringRangeUpperCase]) || ([substring isEqualToString:substringRangeCase])) {


                [autoCompleteArray addObject:curString];                 

            }
        }
    }

}

autoCompleteTableView.hidden = NO;
[autoCompleteTableView reloadData];
}

我的数据 -

  

[{“keyword”:“qwerty”},{“keyword”:“问题论文司法”},{“keyword”:“qwe”},{“keyword”:“quilts”},{“keyword” : “藜”},{ “关键字”: “qwerty0disk”},{ “关键字”: “q”}]

我不知道为什么我的UI变慢了......我也在使用JSONKit

1 个答案:

答案 0 :(得分:0)

NSData *jsonData = [NSData dataWithContentsOfURL:url];是同步通话。 这意味着调用是在主线程中完成的,它将阻止执行过程中的执行。如果连接速度很慢,它将阻塞接口(也在主线程中运行),直到接收到数据为止。

为了避免在dataWithContentOfURL完成时阻塞你的接口,你应该使用gcd或实现一个异步类来获取数据。

Here 是关于gcd和异步连接的讨论

我希望这会有所帮助。