gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:15:43 24 4
gpt4 key购买 nike

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

我的源代码如下

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

}

在 View Controller 类中,
  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{

}

}
}

最佳答案

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

class FriendModel {
var index = ""
var thumbnail = ""
var name = ""
}

let fm0 = FriendModel()
fm0.index = "100"
fm0.thumbnail = "tell.png"
fm0.name = "Phillips"

let fm1 = FriendModel()
fm1.index = "200"
fm1.thumbnail = "ask.png"
fm1.name = "Allen"

var array = [FriendModel]()
array.append(fm0)
array.append(fm1)

// The index below is an index of the array. Do not confuse with the FriendModel.index
let index = array.index {
return $0.thumbnail == "ask.png" && $0.name == "Allen"
}
array.forEach { print($0.name) }

print("Array index:", index ?? "n/a")

array.remove(at: index!)

array.forEach { print($0.name) }

关于arrays - 如何使用 Swift3 删除 Array 中的特定 NSObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41865155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com