swift searchbar and tableview - fatal error: unexpectedly found nil while unwrapping an optional value
swift searchbar and tableview - fatal error: unexpectedly found nil while unwrapping an optional value
我正在尝试通过使用 "Search Bar Search Display Controller" 在我的 tableview 上创建一个搜索工具,就像当用户触摸一个字母时它只会在 tableview 中显示这些项目。表视图上的项目是从网络服务中获取的。我正在学习本教程:Link
而且我无法逃避此错误消息:
fatal error: unexpectedly found nil while unwrapping an Optional value
而且我认为它可能与 searchingDataArray 有关。我尝试了一些调试并在 google 上进行了一些搜索,并检查了包括此处在内的各种网站上的建议,但未能解决问题,现在我有点困惑。下面你可以看到我的代码。怎么解决?
//
// 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()
}
}
}
您的 "searchingDataArray" 声明有问题。
您的代码:
var searchingDataArray:NSMutableArray!
需要像下面这样:
var searchingDataArray:NSMutableArray = NSMutableArray()
我正在尝试通过使用 "Search Bar Search Display Controller" 在我的 tableview 上创建一个搜索工具,就像当用户触摸一个字母时它只会在 tableview 中显示这些项目。表视图上的项目是从网络服务中获取的。我正在学习本教程:Link
而且我无法逃避此错误消息:
fatal error: unexpectedly found nil while unwrapping an Optional value
而且我认为它可能与 searchingDataArray 有关。我尝试了一些调试并在 google 上进行了一些搜索,并检查了包括此处在内的各种网站上的建议,但未能解决问题,现在我有点困惑。下面你可以看到我的代码。怎么解决?
//
// 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()
}
}
}
您的 "searchingDataArray" 声明有问题。
您的代码:
var searchingDataArray:NSMutableArray!
需要像下面这样:
var searchingDataArray:NSMutableArray = NSMutableArray()