gpt4 book ai didi

swift - 使用信号量从解析中获取图像时主线程被锁定

转载 作者:行者123 更新时间:2023-11-30 13:44:59 25 4
gpt4 key购买 nike

我有一个很大的问题。我使用Parse云系统。当我使用解析中的“dispatch_semaphore”获取图像时,主线程被锁定。但是,我认为,在获取图像时我不使用主线程。通常情况下,任务应该按 A、B、C、D 的顺序执行,但应用程序锁定在 B 部分。

谢谢。

    let semaphore1:dispatch_semaphore_t = dispatch_semaphore_create(0)
let semaphore2:dispatch_semaphore_t = dispatch_semaphore_create(0)

let userquery = PFQuery(className: "_User")

userquery.findObjectsInBackground().continueWithSuccessBlock { (task) -> AnyObject? in

let results = task.result as! NSArray

for objectarray in results
{
let object = objectarray as! PFObject
let username = object["username"] as! String
let userpictureThumbnail = object["userPhotoThumbnail"] as! PFFile
userpictureThumbnail.getDataInBackground().continueWithSuccessBlock({ (task2) -> AnyObject? in

let result = task2.result as! NSData
let image = UIImage(data: result)
let imageThumbnail = image

// Section C-) Below codes must be executed but main thread is locked by Section B.
Model.sharedInstance.friendsPictureModel.addItem(username,FriendImageThumbnail:imageThumbnail!)

dispatch_semaphore_signal(semaphore2)
return nil

})

// Section B-) Second, enter the below code . And lock main thread then app freezed.
dispatch_semaphore_wait(semaphore2, DISPATCH_TIME_FOREVER)
}
dispatch_semaphore_signal(semaphore1)
return nil
}

// Section A-) When the block("userquery.findObjectsInBackground().continueWithSuccessBlock") is executed, enter the below code firstly.
dispatch_semaphore_wait(semaphore1, DISPATCH_TIME_FOREVER)

// Section D-) Below codes must be executed in the last.
self.collectionview.reloadData()

最佳答案

您不应该在此处使用信号量。您的 A 部分(大概)在主线程上运行,并且等待将导致其阻塞,直到信号量发出信号为止。

您可以删除所有信号量代码,然后将 self.collectionview.reloadData() 分派(dispatch)到 semaphore2 当前发出信号的主线程上。但是,您还遇到一个问题,即在后台调用 addItem,并且它可能不是线程安全的。

假设您的示例是您的特定问题的简化,您可能在 viewController 和 userquery 之间有一些分离(我们称之为 findTheObjects )。所以目前您会看到类似的内容:

myObjectFinder.findTheObjects()

在这种情况下,您应该传入自己的完成 block ,如下所示:

myObjectFinder.findTheObjects(completion: {
(username, imageThumbnail?) -> Void in
dispatch_async(dispatch_get_main_queue(), {
// do something with the results like...
Model.sharedInstance.friendsPictureModel.addItem(username,FriendImageThumbnail:theResults.imageThumbnail!)
self.collectionview.reloadData()
})
}

然后将从您的 C 部分调用此完成 block 。

关于swift - 使用信号量从解析中获取图像时主线程被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com