[英]How does NSMutableArray change object index you use 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.