当用户开始在UISearchBar中键入时,应用程序崩溃

时间:2014-12-11 19:42:25

标签: ios iphone core-data swift

我在带有核心数据的tableview中设置了一个UISearchBar。当用户开始在搜索栏中输入时,应用程序会在第一个字母上崩溃。我得到的错误是(lldb)。我不确定我做错了什么。有任何想法吗?感谢。

似乎我的问题与filteredQuotes = qs.filteredArrayUsingPredicate(predicate!)有关,但不完全确定我做错了什么。(当我注释掉这一行时,该应用并没有崩溃 - 但搜索并没有要么工作)

//
//  KeepTableViewController.swift
//  Quotey
//
//  Created by Mordechai Levi on 11/25/14.
//  Copyright (c) 2014 Martini. All rights reserved.
//


import UIKit
import CoreData


class KeepTableViewController: UITableViewController, UISearchBarDelegate{

    @IBOutlet weak var searchBar: UISearchBar!

    var filteredQuotes = [AnyObject]()
    var keptQuotes = [NSManagedObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.delegate = self
        searchBar.showsScopeBar = true

        tableView.rowHeight = UITableViewAutomaticDimension

        getCoreData()


        searchDisplayController?.searchResultsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

    }


    func getCoreData(){

        var appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var context : NSManagedObjectContext = appDel.managedObjectContext!
        var req : NSFetchRequest = NSFetchRequest(entityName: "KeptQuotes")

        var error : NSError?

        let fetchedResults = context.executeFetchRequest(req, error: &error) as [NSManagedObject]?

        if let results = fetchedResults {

            keptQuotes = results

        }else{

            println("Could not fetch \(error), \(error!.userInfo)")

        }

        tableView.reloadData()

    }

    @IBAction func cancelPressed(sender: AnyObject) {

        dismissViewControllerAnimated(true, completion: nil) //dismisses the freakin view
    }

    override func preferredStatusBarStyle() -> UIStatusBarStyle {

        return UIStatusBarStyle.LightContent
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
    if !keptQuotes.isEmpty {

        return 1

    }else{

    var label = UILabel(frame: CGRectMake(self.view.center.x, self.view.center.y, 180, 300))
    label.text = "Here is where quotes that you love will show up. To love a quote swipe a quote to the right."
    label.textColor = UIColor(red: 0.573, green: 0.6, blue: 0.627, alpha: 1)
    label.numberOfLines = 0
    label.textAlignment = NSTextAlignment.Center
    label.font = UIFont(name: "AvenirNextCondensed-Medium", size: 17)
    //label.sizeToFit()

    tableView.backgroundView = label
    tableView.separatorStyle = UITableViewCellSeparatorStyle.None


    }
    return 0

    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.

        if tableView == self.searchDisplayController?.searchResultsTableView {

            return filteredQuotes.count

        }else{

            return keptQuotes.count

    }

    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell : QuoteyTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as QuoteyTableViewCell

        var entry : NSManagedObject

        if tableView == self.searchDisplayController!.searchResultsTableView{

            entry = filteredQuotes[indexPath.row] as NSManagedObject

        }else{

            entry = keptQuotes[indexPath.row] as NSManagedObject!

        }

        cell.authorLabel.text = entry.valueForKey("author") as String!
        cell.quoteTextLabel.text = entry.valueForKey("quote") as String!

        cell.quoteTextLabel.sizeToFit()
        cell.selectionStyle = UITableViewCellSelectionStyle.None

        return cell
    }



    func filterContentForSearchText(searchText: String) {

        var qs : NSArray = keptQuotes

        let predicate = NSPredicate(format: "quote contains[c] %@ OR author contains[c] %@", searchText, searchText)

        filteredQuotes = qs.filteredArrayUsingPredicate(predicate!)
        println(filteredQuotes)


    }

    func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {

        self.filterContentForSearchText(searchString)
        return true
    }

    func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {

        self.filterContentForSearchText(searchDisplayController!.searchBar.text)
        return true
    }

}

Also getting this.

2 个答案:

答案 0 :(得分:1)

您已定义了UISearchBar委托,但尚未创建任何UISearchBarDelegate方法,例如searchBar:textDidChange:。尝试委托方法调用时可能会发生崩溃。

答案 1 :(得分:0)

我也面临同样的问题2天。因为我不知道该做什么,因为我尝试了10种不同的解决方案,但它没有起作用

我不知道它是否与你有关。请检查它对我有用。

如果您的应用程序崩溃:

yourTableView.reloadData()

然后使用以下解决方案,否则跳过以下步骤

注意 UITableView's reloadSections代替reloadData

yourTableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.None)

这里根据需要重新加载部分