如果另一个键的值等于某个值,如何在NSObject中更新键的值?

时间:2018-03-03 11:38:04

标签: ios swift4 nsobject

我有一个看起来像这样的NSObject类

class MyItem : NSObject {

    var id: Int
    var name: String

    //other init code here
 }

我想要做的是,在其他课程中,当name等于某事时,更新id的值

现在MyViewController

var myItem = [MyItem]()

例如,如果myItemid=3的内部数组,则将name的值更新为"Ken"

我完全不知道该怎么做。有人可以给我一个提示吗?

2 个答案:

答案 0 :(得分:0)

首先找到我要替换的对象的索引,然后使用索引将其替换为新值

if let row = myItem.index(where: {$0.id == yourId}) { // yourId 3
            myItem[row].name = newValue
        }

答案 1 :(得分:0)

这应该有效:

/// Changes The Name Of A MyItem Object Based On It's ID
///
/// - Parameters:
///   - id: Int
///   - name: String
func changeNameFromID(_ id: Int, to name: String){

    //1. Get The Index Of The Item
    guard let foundIndex = myItem.index(where: { $0.id == id }) else { return }

    //2. Get The MyItem From The Array
    let itemToAppend = myItem[foundIndex]

    //3. Change Its Name
    itemToAppend.name = name


}

然后你可以这样称呼它:

changeNameFromID(3, to: "Ken")