我只是想知道是否有任何方法可以提高我的循环速度,或建议最佳练习,因为我觉得它看起来很糟糕。
以下是代码:
for (index, _) in filteredArray.enumerate() {
if index == 0 || index % 4 == 0 {
let mediaItem = Item()
mediaItem.id = filteredArray[index + 3]
let photoURL = NSURL(string: filteredArray[index + 1])
guard let url = photoURL else { return }
let data = NSData(contentsOfURL: url)
let finishImage = UIImage(data: data!)
mediaItem.Photo = finishImage
mediaItem.orderCount = filteredArray[index + 2]
mediaItem.UUId = filteredArray[index]
self.dataSourceItems.insert(mediaItem)
}
}
答案 0 :(得分:1)
尝试使用dispatch_apply
。这样的事情:
let iterationsCount = filteredArray.count / 4
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_apply(iterationsCount, queue) { i in
let index = i * 4
let mediaItem = Item()
mediaItem.id = filteredArray[index + 3]
let photoURL = NSURL(string: filteredArray[index + 1])
guard let url = photoURL else { return }
let data = NSData(contentsOfURL: url)
let finishImage = UIImage(data: data!)
mediaItem.Photo = finishImage
mediaItem.orderCount = filteredArray[index + 2]
mediaItem.UUId = filteredArray[index]
self.dataSourceItems.insert(mediaItem)
}
请注意,根据您的具体情况,您可能需要1.在访问属性时使用self
封闭内部; 2.如果写入共享内存,请添加一些锁。