swift 中的搜索栏正在使用解析

searchbar in swift using parse

您好,我一直在观看视频来执行此代码,但没有任何效果我尝试尝试使用该代码,但仍然没有发现问题所在。问题是我没有任何错误,当我 运行 代码时,它没有在 tableView 中显示结果。我想做的是我想在解析用户列表中搜索。 这是代码:

func searchBarSearchButtonClicked(searchBar: UISearchBar){
    searchBar.resignFirstResponder()
    print("search word =\(searchBar.text)")

    let usernameQuery = PFQuery(className: "User")
    usernameQuery.whereKey("username", containsString: searchBar.text)

    usernameQuery.findObjectsInBackgroundWithBlock {
        (results: [PFObject]?, error: NSError?) -> Void in

        if error != nil {
            let myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle:UIAlertControllerStyle.Alert)

            let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)

            myAlert.addAction(okAction)

            self.presentViewController(myAlert, animated: true, completion: nil)

            return
        }
        if let objects = results! as? [PFObject]{
            self.searchResults.removeAll(keepCapacity: false)

            for object in objects{
                let usernameid = object.objectForKey("username") as! String
                self.searchResults.append(usernameid)
            }
            dispatch_async(dispatch_get_main_queue()){
                self.myTable.reloadData()
                self.mySearchBar.resignFirstResponder()
            }
        }
    }

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)

    myCell.textLabel?.text = searchResults[indexPath.row]

    return myCell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    mySearchBar.resignFirstResponder()
}

func searchBarCancelButtonClicked(searchBar: UISearchBar){
    mySearchBar.resignFirstResponder()
    mySearchBar.text = ""
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return searchResults.count
}

}

TL;DR

您没有解开来自 UISearchBar 的搜索字符串。

详情

查看Apple's official documentation for UISearchBar时,可以看出text属性是String?.

类型

使用这些知识查看代码时,以下行看起来有点可疑,因为您没有执行任何类型的解包:

usernameQuery.whereKey("username", containsString: searchBar.text)

这可以通过简单的 Playground 测试进一步研究:

import UIKit

let searchBar = UISearchBar()
searchBar.text = "Kumuluzz"
let output = searchBar.text
print("Output: \(output)")

此 playground 中的输出(见右侧栏)如下:

"Output: Optional("Kumuluzz")\n"

这意味着我的用户名必须是 Optional("Kumuluzz") 才能匹配您在 User 基础中的查询。

总而言之,对 text 属性.

应用某种展开