swift 如何将参与者的属性赋给视图控制器属性?

nx7onnlm  于 2023-02-11  发布在  Swift
关注(0)|答案(1)|浏览(119)

我有一个演员是这样的:我想从NewsCache执行元向ViewController分配一个值,但它给出了以下错误:

主操作元隔离属性“cache_data”不能从可发送闭包中变化

actor NewsCache {
    var current_news_on_fetch  : [String:Bool] = [:]
    var news_dict : [String:NewsFeedPageStruct] = [:]
    var time_dict_news : [String:String] = [:]
    var ordered_uuid_news : [String] = []
}
class ViewController : UIViewController  {
   var cache_data : [String : NewsFeedPageStruct] = [:]
   var actor_news = NewsCache()

 func setData(){
        print("Below is the problem")
        Task.detached { [self] in

            self.cache_data = await self.actor_news.get_uuids()//this is the line which produces the error
            await self.reloadSnapshot(hash_news: str_arr.0) //this is in the MainActor
        }
    }

}
fbcarpbf

fbcarpbf1#

你可以使用MainActor.run在主参与者上运行闭包,但是MainActor.run需要一个同步(非async)闭包,所以你需要在调用MainActor.run之前调用get_uuids

func setData_0(){
    Task.detached {
        let cache_data = await self.actor_news.get_uuids()
        await MainActor.run {
            self.cache_data = cache_data
            self.reloadSnapshot()
        }
    }
}

另一个解决方案是将对cache_data的赋值封装在一个立即执行的@MainActor绑定闭包中:

func setData_1(){
    Task.detached {
        await { @MainActor in
            self.cache_data = await self.actor_news.get_uuids()
        }()
        await self.reloadSnapshot()
    }
}

相关问题