在我的应用程序中,我有一个带tableview的viewcontroller,加载它时,它在同一位置上约有12个同时发生的内存错误,我尝试从自定义数组中删除该元素。以下是相关代码
在加载表的 View Controller 中,我访问了如下方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//Some Code
arrangeTableObject.arrangetableSectionsInOrderForNoteType(withFrameId:tableDataSection.frameId.uintValue)
//Some code
return cell
}
在我的另一个swift类rangingTableObject.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)!)
}
}
任何建议或指导表示赞赏。
最佳答案
可能的原因是您在迭代数组时将其从数组中删除。
请尝试以下操作,看看是否有任何问题
tableSections = tableSections.filter { $0.itemType != itemType }
关于ios - 修复自定义类iOS数组的同时内存访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47691655/