簡體   English   中英

如何將數組強制轉換為NSMutableArray以便能夠使用removeObjectAtIndex

[英]How to cast an array as NSMutableArray to be able to use removeObjectAtIndex

我有一組用戶試圖將其轉換為NSMutableArray ,以便能夠使用removeObjectAtIndex ,但它不起作用。 我收到Cast from '[ModelUser]?' to unrelated type 'NSMutableArray' always fails的錯誤Cast from '[ModelUser]?' to unrelated type 'NSMutableArray' always fails Cast from '[ModelUser]?' to unrelated type 'NSMutableArray' always fails如果我嘗試將其'[ModelUser]' does not have a member named 'removeObjectAtIndex' Cast from '[ModelUser]?' to unrelated type 'NSMutableArray' always fails ,或者'[ModelUser]' does not have a member named 'removeObjectAtIndex'

那么如何在這段代碼中從數組中刪除一個對象呢?

query.friend(friendId, command: command, completion: { (result:Bool) -> () in
if result {
   self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
   if let friendR = self.friendRequests as? NSMutableArray{
        friendR.removeObjectAtIndex(indexPath.row)
   }
   println("Friendship deleted")
})

您不能僅通過強制轉換將NSArray轉換為NSMutableArray它們是不同的類。 要從NSArray獲取可變數組,可以在NSArray上調用mutableCopy方法。

但是,在您的情況下,該數組是Swift數組,因此它已經可變。

您需要使用removeAtIndex而不是removeObjectAtIndex來從Swift數組中刪除對象-

query.friend(friendId, command: command, completion: { (result:Bool) -> () in
if result {
   self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
   if self.friendRequests != nil {
        self.friendRequests!.removeAtIndex(indexPath.row)
   }
   println("Friendship deleted")
})

實際上,您僅在進行類型轉換。 您需要使friendR可變以刪除和添加任何對象。

if let friendR = self.friendRequests.mutableCopy() as? NSMutableArray{
    friendR.removeObjectAtIndex(indexPath.row)
}

mutableCopy()和新的NSMutableArray實例將起作用。

您應該使用以下代碼將NSMutableArray例如直接轉換為[YourType]

if var friendR = self.friendRequests as? AnyObject as? [ModelUser] {
    // your swift array handling code here
}

我使用了var關鍵字來啟用將來的friendR突變

您應該從一開始self.friendRequests初始化為NSMutableArray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM