0
 import UIKit

 class MasterTableViewController: UITableViewController,  PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {


//approches for uisearchbar
var searchNotes: [PFObject] = [PFObject]()
var notesSearchController = UISearchController()
var searchActive: Bool = false


// creating array for holding ojects 



var noteObjects: NSMutableArray! = NSMutableArray()
  var v = 0




   override func viewDidLoad() {
     super.viewDidLoad()

    self.notesSearchController = UISearchController(searchResultsController: nil)
    self.notesSearchController.dimsBackgroundDuringPresentation = true

    self.notesSearchController.searchResultsUpdater = self

    // Configure the search controller's search bar
    self.notesSearchController.searchBar.placeholder = "Search for a user"
    self.notesSearchController.searchBar.sizeToFit()
    self.notesSearchController.searchBar.delegate = self
    self.definesPresentationContext = true

    // Set the search controller to the header of the table
    self.tableView.tableHeaderView = self.notesSearchController.searchBar

     print("check")



       }

     override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)



    if v == 0 {
        self.fetchAllObjectsFromLocalDataStore()
        //self.fetchAllObjects()

    }
    }


   // fetching data from local datastore and from parse

   func fetchAllObjectsFromLocalDataStore(){

      let query: PFQuery = PFQuery(className: "Sinhgad")
    query.orderByDescending("createdAt")


    query.fromLocalDatastore()

    query.findObjectsInBackgroundWithBlock { ( objects, error) -> Void in

        if (error == nil) {




            let temp: NSArray = objects as NSArray!

            self.noteObjects = temp.mutableCopy() as! NSMutableArray

             self.tableView.reloadData()


        }else {
        print(error!.userInfo)

        }
      }

    }



    func fetchAllObjects(){

     let query: PFQuery = PFQuery(className: "Sinhgad")
    query.orderByDescending("createdAt")


    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if (error == nil) {




            PFObject.pinAllInBackground(objects, block:  nil )


            self.fetchAllObjectsFromLocalDataStore()

           // self.tableView.reloadData()


        } else {
        print(error?.userInfo)

         }
      }  
      }





   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 Incomplete implementation, return the number of sections
    return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if (self.notesSearchController.active) {
        return self.searchNotes.count
    } else {

    return self.noteObjects.count
    }}


    override func tableView(tableView: UITableView, cellForRowAtIndexPath      indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MasterTableViewCell


    if (self.notesSearchController.active && self.searchNotes.count > indexPath.row) {
        // bind data to the search results cell
         let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        cell.MasterTitleLabel?.text = object["Title"] as? String
        cell.MasterTextLabel.text = object["Fstory"] as? String
        cell.MasterTimeLabel.text = object["Time"] as? String
        cell.MasterLocationLabel.text = object["Location"] as? String

        return cell

    } else {
 let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject



    cell.MasterTitleLabel?.text = object["Title"] as? String
    cell.MasterTextLabel.text = object["Fstory"] as? String
    cell.MasterTimeLabel.text = object["Time"] as? String
    cell.MasterLocationLabel.text = object["Location"] as? String



    return cell
    }}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if (self.notesSearchController.active && self.searchNotes.count > 0) {
        // Segue or whatever you want
        self.performSegueWithIdentifier("openStory", sender: self)

    } else {
    self.performSegueWithIdentifier("openStory", sender: self)
}

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let upcoming: AddNoteTableViewController = segue.destinationViewController as! AddNoteTableViewController

    if (segue.identifier == "openStory"){


        let indexPath = self.tableView.indexPathForSelectedRow!

        let object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject

        upcoming.object = object

        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

}


@IBAction func btnReload(sender: AnyObject) {

    fetchAllObjects()
   }


override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete ){

        let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        // the below for deleting the selected cell's object from server's database
       // object.deleteInBackground()

        //the below for deleting the selected cell's object from localstorage
        object.unpinInBackground()


      self.noteObjects.removeObjectAtIndex(indexPath.row)
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

  }
}
// MARK: - Parse Backend methods

func loadSearchUsers(searchString: String) {

    let query: PFQuery = PFQuery(className: "Sinhgad")
    query.orderByDescending("createdAt")


    // Filter by search string
    query.whereKey("Notes", containsString: searchString)

    self.searchActive = true
    query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in



         if (error == nil) {
            self.searchNotes.removeAll(keepCapacity: false)
            self.searchNotes += objects as [PFObject]!
            self.tableView.reloadData()
        } else {
            // Log details of the failure
            print("search query error: \(error) \(error!.userInfo)")
        }
        self.searchActive = false
    }
}

// MARK: - Search Bar Delegate Methods

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

    // Force search if user pushes button
    let searchString: String = searchBar.text!.lowercaseString
    if (searchString != "") {
        loadSearchUsers(searchString)
    }
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {

    // Clear any search criteria
    searchBar.text = ""

    // Force reload of table data from normal data source
}



// MARK: - UISearchResultsUpdating Methods

// This function is used along with UISearchResultsUpdating for dynamic search results processing
// Called anytime the search bar text is changed
func updateSearchResultsForSearchController(searchController: UISearchController) {

    let searchString: String = searchController.searchBar.text!.lowercaseString
    if (searchString != "" && !self.searchActive) {
        loadSearchUsers(searchString)
    }
}
 }

上面的代码用于从 parse 的服务器和本地存储中检索存储的对象,并在表格视图中显示它们。

一切正常,但我正在尝试实现搜索栏以将搜索功能添加到我的应用程序中。问题是,当我运行应用程序时,它会显示搜索栏,但是当与搜索栏交互时,它会向上移动并消失,并且在输入任何内容时都会消失。

我没有得到任何搜索结果,并且NSLog得到了这个:

  2015-12-03 16:43:48.769 Notes[1015:56944] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UISearchController: 0x7ff2d48165a0>)

我知道缺少一些东西,它不是实现该功能的正确方法。

如果有人知道如何正确地做或缺少什么,请告诉我,如果提问的方式不正确,谢谢和抱歉!

我刚刚发现我的 Pfobject 的 'searchNotes' var 什么都没有,我的意思是它是空的!为此我试过

    cell.MasterTitleLabel?.text = searchNotes["Title"] as! String 

但它给出错误

       cannot subscript  a value of type '[PFObject]' with an index of type 'string'

我知道它是因为我将 searchNotes 声明为

  searchNotes [PFObject] = [PFObject]()

我应该这样做

  searchNotes PFObject = PFObject()

但是当我这样做时,它会出现很多错误,如果有人知道如何解决这个问题,请提供帮助

4

1 回答 1

0

也许您不应该直接使用 PFObject 。

你可以使用另一个类而不是 PFObject

private class object {

var mTitle : String!
var mStory : String!
var mTime : String!
var mLocation : String!
}

And use your code here 

let obj : object = object()
obj.mTitle = PFObject["title"];
...etc
于 2015-12-04T01:32:15.437 回答