swift searchbar和tableview - 致命错误:在解包可选值时意外发现nil

时间:2015-03-18 14:10:51

标签: ios uitableview swift nsmutablearray uisearchbar

我试图通过使用"搜索栏搜索显示控制器"在我的桌面视图上创建搜索工具。比如当用户触摸一个字母时,它只会在tableview中显示这些项目。桌面视图中的项目是从Web服务中获取的。我正在学习本教程:Link

我无法解决此错误消息:

  

致命错误:在解包可选值时意外发现nil

我认为这可能与 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()
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的&#34; searchingDataArray&#34;声明。

您的代码:

var searchingDataArray:NSMutableArray!  

需要如下所示:

var searchingDataArray:NSMutableArray = NSMutableArray()