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

Posted

技术标签:

【中文标题】错误:无法将 [anyobject] 转换为强制类型数组<_>【英文标题】:error : cannot convert [anyobject] to type array<_> in coercion 【发布时间】:2015-12-04 13:14:22 【问题描述】:

我在我的 UITablView 上实现了 UISearchController 并且它工作正常,但我正在尝试实现 PrepareForSegue... 但我的 Func 上出现了一些错误:updateSearchResultsForSearchController

//声明变量//

    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


    

//两行都出现错误

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


self.tableView.reloadData()


in array = (array as NSarray)... 行错误:

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

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

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

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

错误:

<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】:

我不确定 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]

如果你真的希望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)

【讨论】:

@marckhapde 我按照您的建议进行了尝试,但在与搜索栏交互时出现错误 @marckhapde 查看我的整个代码,我更新了我的代码,以便您可以看到所有声明和函数 @marcKhapde 并且错误指向类名...并显示“它不是集合” @marcKhapde 现在您可以看到错误我更新了完整错误及其在与搜索栏交互时发生的错误 看起来 noteObjects 包含您的自定义 PFObject 类型的元素,它不是集合,并且 CONTAINS 谓词仅适用于集合。如果你想在 Swift 中过滤一个数组,你也可以使用 Array 类型的 filter 方法。

以上是关于错误:无法将 [anyobject] 转换为强制类型数组<_>的主要内容,如果未能解决你的问题,请参考以下文章

无法转换任何类型?要键入 AnyObject?从 swift 3 转换为 swift 4 时

尝试保存数组,出现错误 - 无法将类型“[Data]”的值转换为预期的参数类型“[Dictionary<String, AnyObject>]”

求sql中解决连接错误 无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类 型

无法将 HttpContext 强制转换为用户

快速数组无法将“AnyObject”类型的值转换为预期的参数类型@noescape(AnyObject)抛出-> Bool

无法将类型 [NSObject : AnyObject] 转换为字符串