修复自定义类iOS数组的同时内存访问错误

时间:2017-12-07 09:25:55

标签: ios memory-management swift3 crash xcode9.1

在我的应用程序中我有一个带有tableview的viewcontroller,当它加载时,它给了我大约12个同时内存错误,我尝试从我的自定义数组中删除元素。以下是相关代码

在我的viewcontroller中,表加载我已经访问了如下方法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    //Some Code 

    arrangeTableObject.arrangetableSectionsInOrderForNoteType(withFrameId:tableDataSection.frameId.uintValue)

   //Some code
   return cell
}

在我的另一个快速类arrangeTableObject.swift中,我就是这样使用方法

//My custom array is defined as
var tableSections : [TableSection]?

func arrangetableSectionsInOrderForNoteType(type: NoteType){

        var tableIndex = 0

        if tableSectionForItemType(itemType: .tableItemNoteItems) != nil  {

            let noteItemSection = tableSectionForItemType(itemType: .tableItemNoteItems)
            removetableSectionWithFrameId(itemType: . tableItemNoteItems)
            tableSections?.insert(noteItemSection!, at: tableIndex)
            tableIndex += 1
        }


        if let commentSection = tableSectionForItemType(itemType: .tableItemComment) {
            removetableSectionWithFrameId(itemType: .tableItemComment)
            tableSections?.insert(commentSection, at: tableIndex)
            tableIndex+=1
        }


        if tableSectionForItemType(itemType: .tableItemAtAGlance) != nil {

            let otherSection = tableSectionForItemType(itemType: .tableItemOtherItems)
            removetableSectionWithFrameId(itemType: . tableItemOtherItems)
            tableSections?.insert(otherSection!, at: tableIndex)
            tableIndex += 1

        }


    }

//这是显示错误的方法

func removetableSectionWithFrameId(itemType : tableItemType){

        if tableSections?.count != 0 {
            for section in tableSections! {

                if section.itemType == itemType {
                 //Error points to this line below
                        self.tableSections?.remove(at: self.tableSections!.index(of: section)!) 
                }
            }
        }
    }

为了修复我尝试使用以下方法添加同步锁

func sync(lock: NSObject, closure: () -> Void) {
        objc_sync_enter(lock)
        closure()
        objc_sync_exit(lock)
    }

我尝试修改发生错误的部分,如下所示,但它仍然会引发同样的错误

if section.itemType == itemType {
                    sync(lock: tableSections! as NSObject){
                        self.tableSections?.remove(at: self.tableSections!.index(of: section)!)
                }
        }

感谢任何建议或指导。

1 个答案:

答案 0 :(得分:0)

可能的原因是您在迭代时从数组中删除元素。

尝试以下操作,看看您是否有任何问题

tableSections = tableSections.filter { $0.itemType != itemType }
相关问题