点击特定地址单元格时Google Maps搜索栏触发NSRangeException异常求助
Problem Overview
I’m displaying addresses in a search bar, but tapping a corresponding table view cell triggers an immediate crash with this error message:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Relevant code snippet from the tableView(_:didSelectRowAt:) method:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.dismiss(animated: true, completion: nil) let urlpath = "https://maps.googleapis.com/maps/api/geocode/json?address=\(self.searchRes..." // Remaining code to handle the API request }
Solution Breakdown
This is a classic array out-of-bounds error—you’re trying to access index 1 of an array that only contains one element (valid index range is [0..0]). Here’s how to fix it step by step:
1. Fix Invalid Array Index Access
The crash occurs because you’re either hardcoding index 1 when accessing self.searchRes, or you’re not validating that the selected row’s index exists in the array. Replace unsafe index access with a safety check and use the tapped row’s actual index:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.dismiss(animated: true, completion: nil) // Guard against out-of-bounds index guard indexPath.row < self.searchRes.count else { print("Selected index is outside the range of search results!") return } // Get the address from the tapped row let selectedAddress = self.searchRes[indexPath.row] // URL-encode the address to handle spaces/special characters (critical for API requests) guard let encodedAddress = selectedAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { print("Failed to encode address for API request!") return } let urlpath = "https://maps.googleapis.com/maps/api/geocode/json?address=\(encodedAddress)" // Proceed with your API request logic... }
2. Debug the searchRes Array
To prevent this issue from recurring, add debug prints when you populate searchRes to verify its contents and count:
// When you load or update your search results: print("Total search results: \(searchRes.count)") print("Search results content: \(searchRes)")
This will help you confirm if the array is being populated correctly and matches your expected number of elements.
3. Handle Edge Cases
Add logic to handle empty search results (e.g., show a "No results found" label in your table view) to prevent users from tapping empty cells entirely.
内容的提问来源于stack exchange,提问作者user9395315

