当在uisearchbar中输入文本时,uitableview不会重新加载到最新的数组

时间:2014-08-05 09:58:01

标签: ios uisearchbar

我正在使用这种方法从foursquare获取场地。当我点击搜索栏加载场地时,它显示表减去一次迭代,(例如,如果我搜索“SAMSUNG”它重新加载“SAMSUN”的表视图)但我可以从nslog看到该数据从四个方格中检索并存储在nsarray中,但它不会显示在表格中。

- (void)getFourSquare:(NSString *)SearchString
{
NSString *CLIENT_ID = @"CLIENT_ID";
NSString *CLIENT_SECRET = @"CLIENT_SECRET";
NSString *searchString = SearchString;

NSString *requestString =[NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?near=perth&intent=browse&radius=20000&limit=25&query=%@&client_id=%@&client_secret=%@&v=20140710",searchString,CLIENT_ID, CLIENT_SECRET];
NSURL *urlString = [NSURL URLWithString:requestString];

[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:urlString] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (!error) {
        NSArray *latestFSquares = [self fetchData:data];
        fsquares = [NSMutableArray arrayWithCapacity:10];

        if (latestFSquares) {
            for (NSDictionary *fSquareDic in latestFSquares) {
                foursquare *fsquare = [[foursquare alloc] init];
                fsquare.name = [fSquareDic objectForKey:@"name"];
                NSLog(@"name : %@ ",[fSquareDic objectForKey:@"name"]);
                [fsquares addObject:fsquare];
            };
        }

    }
        [self.tableView reloadData];
}];

  }

我用来更新搜索文本的方法如下,我尝试在下面的函数中使用tableView重新加载,但仍然显示减去一次迭代。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self getFourSquare:searchText];
}

1 个答案:

答案 0 :(得分:1)

问题在于以下一行

fsquares = [NSMutableArray arrayWithCapacity:10];

您每次都在创建NSMutableArray的新引用,这是错误的。要解决此问题,请初始化fsquares一次并更改以下值

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
     if(!fsquares)
         fsquares = [NSMutableArray arrayWithCapacity:10];

     [self getFourSquare:searchText];    
}

删除函数getFourSquare内的初始化。

<强> Update

[fsquares removeAllObjects]移至以下栏目中的以下行

if (latestFSquares) {
    [fsquares removeAllObjects];
}

应该修复。

干杯。