这个问题似乎被多次询问,但我找不到对我的问题的好答案。
基本上autoreleasepool
使用的内存似乎不会在函数调用之后立即释放,而是在内存中保留一段时间,如果在for循环中多次调用它,最终会导致应用程序崩溃。
我也试过release
无济于事(如果我做错了,请告诉我。)
我的问题是在函数调用之后我怎么能 // let _ = selectedImages.map { $0.localSync() }
for index in 0..<selectedImages.count {
autoreleasepool { () -> Void in
let _ = selectedImages[index].localSync()
}
}
func localSync() -> SyncStatus {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).first!
let dataPath = documentsDirectory.appendingPathComponent("Images", isDirectory: true)
try! FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
let uuid = NSUUID().uuidString
let imagePath = dataPath.appendingPathComponent("\(uuid).jpg")
if self.syncStatus != .no && self.syncStatus != .localError { // self.localPath == nil
return self.syncStatus
}
if let data = UIImageJPEGRepresentation(self.image, 0.96),
let _ = try? data.write(to: imagePath) {
self.localPath = imagePath
self.syncStatus = .localOk
self.image = nil
} else {
self.localPath = nil
self.syncStatus = .localError
}
return self.syncStatus
}
那段内存。贝娄你会找到相关的代码:
//Class Properties
var currentPage = 0
var previousPage = 0
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
updatePage(scrollView)
return
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView){
updatePage(scrollView)
return
}
func updatePage(scrollView: UIScrollView) {
let pageWidth:CGFloat = scrollView.frame.width
let current:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1
currentPage = Int(current)
if currentPage == 0 {
// DO SOMETHING
}
else if currentPage == 1{
// DO SOMETHING
}
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
if previousPage != currentPage {
previousPage = currentPage
if currentPage == 0 {
//DO SOMETHING
}else if currentPage == 1 {
// DO SOMETHING
}
}
}
答案 0 :(得分:0)
您可以尝试创建一个OperationQueue
,maxConcurrentOperationCount
设置为1.我遇到了这样的问题,它对我有用。
lazy var imgSyncQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Image Sync Queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
然后将操作添加到此队列
imgUploadQueue.addOperation(BlockOperation(block: { /*sync code here*/ })