如何使用Swift3删除Array中的特定NSObject

时间:2017-01-26 02:46:47

标签: arrays swift xcode nsobject

我与朋友联系信息制作了桌面视图 如果触摸,每个单元格都有按钮,
我想将信息插入选定的朋友阵列
(通过数组,我制作了另一个小视图,与朋友列表一起向上滑动) 但如果再次使用按钮,则 我想删除所选好友阵列中的好友信息 我知道如何附加到数组,
但我不知道如何擦除数组中的特定项(NSObject) 不使用索引。

我的源代码在

之下
class FriendModel : NSObject {
   dynamic var index : ""
   dynamic var thumbnail : ""
   dynamic var name : "" 

}

和在视图控制器类中,

  var selectedList = [FriendModel]()

@IBAction func SelectAct(_ sender: Any) {

    let chooseBtn = sender as! UIButton

    let indexPath = NSIndexPath(row: chooseBtn.tag, section:0)
    let cell = tableView.cellForRow(at: indexPath as IndexPath) as! FriendsListSendCell

    // when selected button is pushed
    if chooseBtn.isSelected == true {
        chooseBtn.isSelected = false
        count = count! - 1

        if self.count! < 1 {
            self.windowShowUp = false
            UIView.animate(withDuration: 0.1, delay: 0.1, options: [], animations:{self.selectedBoard.center.y += 80 }, completion: nil)
            self.checkNumLabel.text = ""
        }else{

        }
     //////////////////////////here////////////////////////////  
     //////////////////how to erase the FriendModel(NSObject) in selectedList.

    }
    //when the unselected button is pushed 
    else {

        //instance for append the friend info
        let friendInfo = FriendModel()


        chooseBtn.isSelected = true
        count = count! + 1

        friendInfo.thumbnail = cell.thumbnail
        friendInfo.name = cell.nameLabel.text!

        //add friend info to selectedList
        self.selectedList.append(friendInfo)
        print("\(self.selectedList)")



        if self.windowShowUp! == false{
            self.windowShowUp = true
            UIView.animate(withDuration: 0.1, delay: 0.1, options: [], animations:{self.selectedBoard.center.y -= 80 }, completion: nil)

        }else{

        }

    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用index(where:)获取对象的索引,然后使用remove项目位于索引位置。

onCreate()

答案 1 :(得分:1)

您可以使用MirekE的解决方案,但这是另一种解决方案。

第一步是确定FriendModel对象上的唯一标识符,例如id属性。

然后在你的模型上,因为它是一个NSObject,覆盖isEqual函数,如下所示:

override public func isEqual(object: AnyObject?) -> Bool {
    let friend = object as? FriendModel
    if self.id == friend?.id { return true }
    return false
}

此时,您可以使用所需的迭代形式在数组中查找元素并使用remove。