iOS自动完成从JSON而不是数组

时间:2014-02-08 13:08:09

标签: ios json autocomplete

我想用tableView进行自动完成,因为我有这个功能:

-(AutocompletionTableView *)autoCompleter
{
    if (!_autoCompleter)
    {
        NSMutableDictionary *options = [NSMutableDictionary dictionaryWithCapacity:2];
        [options setValue:[NSNumber numberWithBool:YES] forKey:ACOCaseSensitive];
        [options setValue:nil forKey:ACOUseSourceFont];  

        _autoCompleter = [[AutocompletionTableView alloc] initWithTextField:self.textField inViewController:self withOptions:options];
        _autoCompleter.autoCompleteDelegate = self;
        _autoCompleter.suggestionsDictionary = [NSArray arrayWithObjects:@"hostel",@"caret",@"carrot",@"house",@"horse", nil];
    }

    return _autoCompleter;
}

问题:

我希望从远程JSON文件中自动完成,而不是从数组中自动完成。

我对如何做这样的事情有任何想法?代码片段非常有用,因为我是iOS开发中的新手。

1 个答案:

答案 0 :(得分:0)

使用 NSURLConnection 向服务器发出请求后,您应收到包含以下数据的 NSData

["hostel","caret","carrot","house","horse"]

这个NSData是这样的:

NSString* data = @"[\"hostel\",\"caret\",\"carrot\",\"house\",\"horse\"]";
NSData* dataReceived = [data dataUsingEncoding:NSUTF8StringEncoding];

因此,要将其转换为数组,您可以调用 NSJSONSerialization ,如下所示:

NSError *jsonError = nil;
NSArray *responseDictionary = [NSJSONSerialization JSONObjectWithData:dataReceived options:0 error:&jsonError];
if(jsonError == nil)
{
    _autoCompleter.suggestionsDictionary = responseArray;
}