[英]swift searchbar and tableview - fatal error: unexpectedly found nil while unwrapping an optional value
I'm trying to make a search facility on my tableview by using "Search Bar Search Display Controller" like when user touches a letter it will only display those items in the tableview. 我正在尝试通过使用“搜索栏搜索显示控制器”在我的表视图上建立搜索功能,例如当用户触摸字母时,它将仅在表视图中显示这些项目。 Item's on tableview are fetched from a webservice. tableview上的项目是从Web服务获取的。 I was following this tutorial: Link 我正在关注本教程: 链接
And i cannot get away with this error message: 而且我无法摆脱这个错误信息:
fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil
And i think it might be about searchingDataArray . 我想这可能是关于searchingDataArray。 I tried some debugging and made some search on google and examined suggestions on various sites including here but yet failed to fix the problem and now i'm little bit confused. 我尝试了一些调试,并在Google上进行了一些搜索,并检查了包括此处在内的各种站点的建议,但未能解决问题,现在我有些困惑。 Below you can see my code. 在下面您可以看到我的代码。 How can fix it? 如何解决?
//
// ThirdViewController.swift
// myApp
//
// Created by Timur Aykut Yildirim on 17/03/15.
// Copyright (c) 2015 Timur Aykut Yildirim. All rights reserved.
//
import UIKit
class ThirdViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var manufacturerSearchBar: UISearchBar!
@IBOutlet var allManufacturers: UITableView!
var myData:NSMutableArray = NSMutableArray()
var is_searching:Bool! // flag for whether search is active or not
var searchingDataArray:NSMutableArray! // sorted search results will be here
func getAllManufacturers(){
var url : String = "http://00.00.000.000/myWebService"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
var userMomentList:NSMutableArray = NSMutableArray()
self.myData = jsonResult.objectForKey("result") as NSMutableArray
//println("AAAAAAAAAAAAA")
println("this is myData dude: \(self.myData)")
dispatch_async(dispatch_get_main_queue(), {
self.allManufacturers.reloadData()
})
//println("QQQQQQQQQQQQQ")
} else {
// couldn't load JSON, look at error
println("jsonResult is nil")
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getAllManufacturers()
//println("this is myData: \(myData)")
is_searching = false
self.allManufacturers.registerClass(UITableViewCell.self, forCellReuseIdentifier: "allMAN_cell_identifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if is_searching == true{
return self.searchingDataArray.count
}
else{
return self.myData.count //Currently Giving default Value
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "allMAN_cell_identifier")
if is_searching == true {
cell.textLabel?.text = searchingDataArray[indexPath.row] as NSString
}
else {
var data = self.myData.objectAtIndex(indexPath.row) as NSDictionary
cell.textLabel?.text = data.objectForKey("text") as NSString
//cell.detailTextLabel?.text = data.objectForKey("item_value") as NSString
}
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let chosenCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell;
// println(chosenCell.textLabel!.text!)
let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row+1) and it's: \(chosenCell.textLabel!.text!)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
if (chosenCell.accessoryType == UITableViewCellAccessoryType.Checkmark) {
chosenCell.accessoryType = UITableViewCellAccessoryType.None;
} else {
chosenCell.accessoryType = UITableViewCellAccessoryType.Checkmark;
}
}
// this method does all the search trick
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
if searchBar.text.isEmpty{
is_searching = false
allManufacturers.reloadData()
} else {
println(" search text %@ ",searchBar.text as NSString)
is_searching = true
searchingDataArray.removeAllObjects()
for var index = 0; index < myData.count; index++
{
var currentString = myData.objectAtIndex(index) as String
if currentString.lowercaseString.rangeOfString(searchText.lowercaseString) != nil {
searchingDataArray.addObject(currentString)
}
}
allManufacturers.reloadData()
}
}
}
Problem with your "searchingDataArray" declaration. 您的“ searchingDataArray”声明存在问题。
Your code: 您的代码:
var searchingDataArray:NSMutableArray!
Needs to be like the following: 需要像下面这样:
var searchingDataArray:NSMutableArray = NSMutableArray()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.