【问题标题】:Simultaneous memory access error while inserting element in array在数组中插入元素时同时出现内存访问错误
【发布时间】:2018-06-14 23:42:17
【问题描述】:

我在下面的方法中遇到了同时内存访问错误。谁能建议我应该如何修改它以消除此错误并保持功能完整。

func add(myItem:String, atIndex index:Int){

    if self.myItems!.count-1 > index {
        self.myItems?.insert(myItem, at: index)
    }
    else{

        while index > self.myItems!.count {
            //getting error in this insert statement below
            self.myItems?.insert(myItemPlaceHolder, at: self.myItems!.count)
        }

        self.myItems?.append(myItem)
    }
}

这就是数组的定义var myItems : [String]?

感谢任何建议。

【问题讨论】:

  • 使用append(contentsOf:) 代替while 循环

标签: ios memory-management swift4 xcode9.2 simultaneous-calls


【解决方案1】:

尝试更改 var myItems : [String] = [String]() 并在您的函数中进行适当的更改,如下所示

func add(myItem:String, atIndex index:Int){

        if self.myItems.count-1 > index {
            self.myItems.insert(myItem, at: index)
        }
        else{

            while index > self.myItems.count {
                self.myItems.insert(myItemPlaceHolder, at: self.myItems.count)
            }

            self.myItems.append(myItem)
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2016-06-19
    相关资源
    最近更新 更多