【问题标题】:Error while implementing UISearchController for PFobjects为 PFobjects 实现 UISearchController 时出错
【发布时间】:2015-12-03 19:21:35
【问题描述】:
      import UIKit

    class MasterTableViewController: UITableViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UISearchResultsUpdating {


var searchNotes: PFObject = PFObject()
var filteredNotes =  [String]()

var resultSearchController = UISearchController()
var searchActive: Bool = false



 // creating array for holding ojects 



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




override func viewDidLoad() {
    super.viewDidLoad()

    self.resultSearchController = UISearchController(searchResultsController: nil)
    self.resultSearchController.searchResultsUpdater = self

    self.resultSearchController.dimsBackgroundDuringPresentation = false
    self.resultSearchController.searchBar.sizeToFit()

    self.tableView.tableHeaderView = self.resultSearchController.searchBar

    self.tableView.reloadData()





       }

   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.resultSearchController.active
    {
        return self.filteredNotes.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.resultSearchController.active
    {
        cell.textLabel?.text = self.filteredNotes[indexPath.row]





        searchNotes  = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        cell.MasterTitleLabel?.text = searchNotes["Title"] as? String

        cell.MasterTextLabel.text = searchNotes["Fstory"] as? String
        cell.MasterTimeLabel.text = searchNotes["Time"] as? String
        cell.MasterLocationLabel.text =  searchNotes["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

    print(searchNotes)

return cell
    }}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if self.resultSearchController.active
    {
    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()
    print(searchNotes)
 }


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 ){

        if self.resultSearchController.active
        {


        }else{



        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)

  }
}    
func updateSearchResultsForSearchController(searchController: UISearchController) {

    self.filteredNotes.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)

    let array = (self.noteObjects as NSArray).filteredArrayUsingPredicate(searchPredicate)

    self.filteredNotes = array as! [String]
    self.tableView.reloadData()



    print(searchNotes)



}
}

我正在尝试实现 uisearchbar,但我不知道在尝试运行应用程序时出现错误,如果有人知道什么是错误的,请告诉我

出现的错误:

2015-12-04 00:41:31.915 Notes[1950:228026] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can only call -[PFObject init] on subclasses conforming to PFSubclassing.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106ff8e65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000108d37deb objc_exception_throw + 48
    2   CoreFoundation                      0x0000000106ff8d9d +[NSException raise:format:] + 205
    3   Notes                               0x00000001059abac6 -[PFObject init] + 146
    4   Notes                               0x000000010597c5b0 _TTOFCSo8PFObjectcfMS_FT_S_ + 16
    5   Notes                               0x000000010597c2e7 _TFCSo8PFObjectCfMS_FT_S_ + 71
    6   Notes                               0x000000010597b2a5 _TFC5Notes25MasterTableViewControllercfMS0_FT5coderCSo7NSCoder_GSqS0__ + 37
    7   Notes                               0x000000010597b3fd _TToFC5Notes25MasterTableViewControllercfMS0_FT5coderCSo7NSCoder_GSqS0__ + 45
    8   UIKit                               0x0000000107bd417f -[UIClassSwapper initWithCoder:] + 241
    9   UIKit                               0x0000000107da67ba UINibDecoderDecodeObjectForValue + 705
    10  UIKit                               0x0000000107da64f0 -[UINibDecoder decodeObjectForKey:] + 278
    11  UIKit                               0x0000000107bd3e55 -[UIRuntimeConnection initWithCoder:] + 180
    12  UIKit                               0x0000000107bd4589 -[UIRuntimeEventConnection initWithCoder:] + 60
    13  UIKit                               0x0000000107da67ba UINibDecoderDecodeObjectForValue + 705
    14  UIKit                               0x0000000107da697b UINibDecoderDecodeObjectForValue + 1154
    15  UIKit                               0x0000000107da64f0 -[UINibDecoder decodeObjectForKey:] + 278
    16  UIKit                               0x0000000107bd3067 -[UINib instantiateWithOwner:options:] + 1255
    17  UIKit                               0x0000000107f39a04 -[UIStoryboard instantiateViewControllerWithIdentifier:] + 181
    18  UIKit                               0x0000000107f3e6c8 -[UIStoryboardSegueTemplate instantiateOrFindDestinationViewControllerWithSender:] + 90
    19  UIKit                               0x0000000107f3e925 -[UIStoryboardSegueTemplate _perform:] + 52
    20  UIKit                               0x0000000107f3ec07 -[UIStoryboardSegueTemplate perform:] + 156
    21  UIKit                               0x00000001078198c8 -[UIApplication sendAction:to:from:forEvent:] + 92
    22  UIKit                               0x0000000107988328 -[UIControl sendAction:to:forEvent:] + 67
    23  UIKit                               0x00000001079885f4 -[UIControl _sendActionsForEvents:withEvent:] + 311
    24  UIKit                               0x0000000107987724 -[UIControl touchesEnded:withEvent:] + 601
    25  UIKit                               0x0000000107888bcf -[UIWindow _sendTouchesForEvent:] + 835
    26  UIKit                               0x0000000107889904 -[UIWindow sendEvent:] + 865
    27  UIKit                               0x000000010783829a -[UIApplication sendEvent:] + 263
    28  UIKit                               0x0000000117611ff9 -[UIApplicationAccessibility sendEvent:] + 77
    29  UIKit                               0x00000001078124cb _UIApplicationHandleEventQueue + 6844
    30  CoreFoundation                      0x0000000106f24a31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    31  CoreFoundation                      0x0000000106f1a8d7 __CFRunLoopDoSources0 + 423
    32  CoreFoundation                      0x0000000106f19e13 __CFRunLoopRun + 867
    33  CoreFoundation                      0x0000000106f19828 CFRunLoopRunSpecific + 488
    34  GraphicsServices                    0x000000010ab6aad2 GSEventRunModal + 161
    35  UIKit                               0x0000000107817d44 UIApplicationMain + 171
    36  Notes                               0x0000000105971afd main + 109
    37  libdyld.dylib                       0x0000000109ebd92d start + 1
    38  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

我正在尝试实现 uisearchbar,但我不知道在尝试运行应用程序时出现错误,如果有人知道什么是错误的,请告诉我

【问题讨论】:

    标签: ios swift parse-platform swift2


    【解决方案1】:

    这个错误是由var searchNotes: PFObject = PFObject() 行引起的,这意味着你不能直接实例化对象。根据Developers Guide,您需要使用 Parse Cloud 中的实际名称来实例化您的对象。像这样的:

    var searchNotes = PFObject(className:"YourObjectName")
    

    更新。

    阅读您的代码我假设您想使用 PFObject 的数组而不是单个对象。

    更新。

    我打赌你下一个错误是由这两行引起的:

    let array = (self.noteObjects as NSArray).filteredArrayUsingPredicate(searchPredicate)
    self.filteredNotes = array as! [String]
    

    因为您尝试将String 的谓词与PFObjects 一起使用。但是这个问题与原著无关。

    好的。我猜你需要这个:

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    var array = (self.noteObjects as! [PFObject]).map { (obj) -> String 
      obj["Title"]
    }
    array = (array as NSArray).filteredArrayUsingPredicate(searchPredicate)
    

    【讨论】:

    • 按照您的建议尝试,但现在视图正在显示,但是当我尝试在我的搜索栏中输入内容时显示错误
    • 2015-12-04 01:31:22.829 Notes[2212:253640] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“不能在集合中使用/包含运算符 { Fstory = "Trial";位置 = 卡利;时间=“9:00”;标题=“十二月”; }(不是集合)'
    • 类 AppDelegate: UIResponder, UIApplicationDelegate { signal SIGABART
    • 如果我想搜索存储在本地存储中的数据怎么办??
    • 它在这一行 { (obj) -> String (consecutive statements) 中显示错误预期声明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多