错误:无法将[anyobject]转换为强制类型数组

时间:2021-09-18 15:21:11

i implemented UISearchController on my UITablView and its Working Fine but am trying to implement the PrepareForSegue{...} but am getting some errors on my Func: updateSearchResultsForSearchController

我在我的UITablView上实现了UISearchController及其工作正常,但我正在尝试实现PrepareForSegue {...}但是我的Func上出现了一些错误:updateSearchResultsForSearchController

//declaring variables//

    var searchNotes = PFObject(className: "MyClass")
    var filteredNotes: NSMutableArray! = NSMutableArray()

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

.................................. ..................

     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()
    self.definesPresentationContext = true   //self takes priority over the searchController presentation
    self.resultSearchController.hidesNavigationBarDuringPresentation = false
 }

   // 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] as? String





        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



        return cell
    }}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var object :AnyObject?
    if self.resultSearchController.active{
        object = filteredNotes[indexPath.row]
        print(filteredNotes[indexPath.row])
        self.performSegueWithIdentifier("openStory", sender: self)

    } else {

        object = self.noteObjects[indexPath.row]
        print(noteObjects[indexPath.row])

        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!

        if self.resultSearchController.active
        {

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



            upcoming.object = object

        }
        else{

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

            upcoming.object = object

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

   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)
    self.filteredNotes.removeAllObjects()

    //        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    //
    //        let array = (self.noteObjects as NSArray).filteredArrayUsingPredicate(searchPredicate)
    //
    //        self.filteredNotes = array as! [String]

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


    }

//error occurring here in both lines

//这两行都出现错误

    array = (array as NSArray).filteredArrayUsingPredicate(searchPredicate) as Array
    self.filteredNotes = array as  Array


self.tableView.reloadData()
}
}

in array = (array as NSarray)... line error:

在array =(数组为NSarray)...行错误:

  MasterTableViewController.swift:281:36: Cannot convert value of type '[AnyObject]' to type 'Array<_>' in coercion

in self.filterednotes...... line error:

在self.filterednotes ......行错误:

 MasterTableViewController.swift:282:30: Cannot convert value of type '[[PFObject]]' to type 'Array<_>' in coercion

don't know how to fix this if anybody know then please tell me thanks

如果有人知道的话,不知道如何解决这个问题,请告诉我谢谢

error:

<Sinhgad: 0x7fa53c02c5c0, objectId: DJ0oIHi9ir, localId: (null)> {
Fstory = "test 33";
Location = "test 3333";
Time = "test 333";
Title = "test 3";
}
2015-12-05 12:50:32.604 Notes[920:81965] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't use in/contains operator with collection <Sinhgad: 0x7fa53c02c5c0, objectId: DJ0oIHi9ir, localId: (null)> {
Fstory = "test 33";
Location = "test 3333";
Time = "test 333";
Title = "test 3";
 } (not a collection)'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000110187e65 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x0000000111ec6deb objc_exception_throw + 48
2   Foundation                          0x000000011059e6b1 -[NSCompoundPredicate evaluateWithObject:substitutionVariables:] + 0
3   Foundation                          0x0000000110575719 -[NSPredicateOperator performOperationUsingObject:andObject:] + 286
4   Foundation                          0x0000000110574e3c -[NSComparisonPredicate evaluateWithObject:substitutionVariables:] + 313
5   Foundation                          0x0000000110574c94 _filterObjectsUsingPredicate + 398
6   Foundation                          0x0000000110574a84 -[NSArray(NSPredicateSupport) filteredArrayUsingPredicate:] + 279
7   Notes                               0x000000010eb087c7 _TFC5Notes25MasterTableViewController38updateSearchResultsForSearchControllerfS0_FCSo18UISearchControllerT_ + 919
8   Notes                               0x000000010eb0896a _TToFC5Notes25MasterTableViewController38updateSearchResultsForSearchControllerfS0_FCSo18UISearchControllerT_ + 58
9   UIKit                               0x00000001113d355d -[UISearchController _performAutomaticPresentation] + 1029
10  UIKit                               0x0000000110d98185 -[UISearchBar(UISearchBarStatic) _searchFieldBeginEditing] + 220
11  UIKit                               0x00000001207d69a8 -[UISearchBarAccessibility _searchFieldBeginEditing] + 45
12  UIKit                               0x00000001109a88c8 -[UIApplication sendAction:to:from:forEvent:] + 92
13  UIKit                               0x0000000110b17328 -[UIControl sendAction:to:forEvent:] + 67
14  UIKit                               0x0000000110b175f4 -[UIControl _sendActionsForEvents:withEvent:] + 311
15  UIKit                               0x00000001113884d8 -[UITextField willAttachFieldEditor:] + 800
16  UIKit                               0x0000000110b214f1 -[UIFieldEditor becomeFieldEditorForView:] + 938
17  UIKit                               0x000000011137c979 -[UITextField _becomeFirstResponder] + 210
18  UIKit                               0x0000000110d9bdc5 -[UISearchBarTextField _becomeFirstResponder] + 96
19  UIKit                               0x000000011137c737 -[UITextField __resumeBecomeFirstResponder] + 52
20  UIKit                               0x0000000110d9c1ce __45-[UISearchBarTextField _becomeFirstResponder]_block_invoke + 447
21  UIKit                               0x00000001109b2bd6 _runAfterCACommitDeferredBlocks + 317
22  UIKit                               0x00000001109c6335 _cleanUpAfterCAFlushAndRunDeferredBlocks + 95
23  UIKit                               0x00000001109d2227 _afterCACommitHandler + 90
24  CoreFoundation                      0x00000001100b3367 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
25  CoreFoundation                      0x00000001100b32d7 __CFRunLoopDoObservers + 391
26  CoreFoundation                      0x00000001100a8f2b __CFRunLoopRun + 1147
27  CoreFoundation                      0x00000001100a8828 CFRunLoopRunSpecific + 488
28  GraphicsServices                    0x0000000113cf9ad2 GSEventRunModal + 161
29  UIKit                               0x00000001109a6d44 UIApplicationMain + 171
30  Notes                               0x000000010eafec0d main + 109
31  libdyld.dylib                       0x000000011304c92d start + 1
32  ???                                 0x0000000000000001 0x0 + 1
   )

libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

1 个解决方案

#1


0  

I am not sure how noteObjects is defined in your code. I think your issue is you are casting way too much, and trying to cast to just plain "Array" is not what you want. Try something like the below.

我不确定如何在代码中定义noteObjects。我认为你的问题是你投射的方式太多了,并且试图投射到简单的“阵列”并不是你想要的。尝试类似下面的内容。

var noteObjects = [PFObject]()
var filteredNotes = [PFObject]()
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (noteObjects as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredNotes = array as! [PFObject]

If you really want noteObjects and filteredNotes to be of type NSMutableArray rather than Swift arrays, you can try the following.

如果您确实希望noteObjects和filteredNotes类型为NSMutableArray而不是Swift数组,则可以尝试以下操作。

var noteObjects = NSMutableArray()
var filteredNotes = NSMutableArray()
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = noteObjects.filteredArrayUsingPredicate(searchPredicate)
filteredNotes = NSMutableArray(array: array)

#1


0  

I am not sure how noteObjects is defined in your code. I think your issue is you are casting way too much, and trying to cast to just plain "Array" is not what you want. Try something like the below.

我不确定如何在代码中定义noteObjects。我认为你的问题是你投射的方式太多了,并且试图投射到简单的“阵列”并不是你想要的。尝试类似下面的内容。

var noteObjects = [PFObject]()
var filteredNotes = [PFObject]()
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (noteObjects as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredNotes = array as! [PFObject]

If you really want noteObjects and filteredNotes to be of type NSMutableArray rather than Swift arrays, you can try the following.

如果您确实希望noteObjects和filteredNotes类型为NSMutableArray而不是Swift数组,则可以尝试以下操作。

var noteObjects = NSMutableArray()
var filteredNotes = NSMutableArray()
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = noteObjects.filteredArrayUsingPredicate(searchPredicate)
filteredNotes = NSMutableArray(array: array)