当UITextField文本达到一定长度时,为什么我的应用程序崩溃了?

时间:2014-10-07 20:34:57

标签: objective-c xcode google-maps-sdk-ios

我正在使用Google Places API for iOS。我正致力于创建自动填充功能,并且我将建议放在4个按钮中(原因与此问题无关),但我注意到,一旦用户输入达到一定长度,应用程序崩溃。我的代码如下:

_request = [[NSMutableURLRequest alloc]init];
_escapedUrlString = [_textField.text stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding
    _requestURL = [NSString stringWithFormat: @"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&key=mykey",_escapedUrlString];
[_request setURL: [NSURL URLWithString:_requestURL]];
[_request setHTTPMethod:@"GET"];
NSURLResponse *requestResponse;
_requestHandler = [NSURLConnection sendSynchronousRequest:_request returningResponse:&requestResponse error:nil];
_requestReply = [[NSString alloc]initWithBytes: [_requestHandler bytes] length: [_requestHandler length] encoding: NSASCIIStringEncoding];
_data = [_requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:_data options:0 error:nil];
[_pred1 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:0]objectForKey:@"description"] forState: UIControlStateNormal];
[_pred2 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:1]objectForKey:@"description"] forState: UIControlStateNormal];
[_pred3 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:2]objectForKey:@"description"] forState: UIControlStateNormal];
[_pred4 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:3]objectForKey:@"description"] forState: UIControlStateNormal];

在这种情况下,_pred1,_pred2,_pred3,_pred4是我的按钮,_textField显然是输入用户输入的文本字段。此代码位于 - (IBEvent)editChange方法中。代码工作,自动完成预测填充按钮标题。

我的问题是,一旦我输入一定长度的字符串,我会收到以下错误:

2014-10-07 16:21:48.740 maptest[41319:529100] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (1) beyond bounds (1)'

我的假设是,随着输入字符串越来越长,预测的数量会缩短,因此在后面的标题中没有任何内容。但是,一旦返回的预测数量减少,我就不知道如何阻止应用程序崩溃。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你在说

[_pred1 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:0]objectForKey:@"description"] forState: UIControlStateNormal];
[_pred2 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:1]objectForKey:@"description"] forState: UIControlStateNormal];
[_pred3 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:2]objectForKey:@"description"] forState: UIControlStateNormal];
[_pred4 setTitle: [[[_json objectForKey:@"predictions"] objectAtIndex:3]objectForKey:@"description"] forState: UIControlStateNormal];

...不首先查看 objectAtIndex:0objectAtIndex:1等等。先看看。