- 已关闭**。此问题为opinion-based。当前不接受答案。
- 想要改进此问题吗?**请更新此问题,以便editing this post可以用事实和引文来回答。
9分钟前就关门了。
Improve this question
下面的代码:
/* @MainActor */ class Locator : NSObject, ObservableObject
{
private let locationManager: CLLocationManager
private var authorizationContinuation: CheckedContinuation<CLAuthorizationStatus, Never>?
@Published var authorizationStatus: CLAuthorizationStatus
@Published var location: CLLocation?
@Published var error: Error?
override init()
{
locationManager = CLLocationManager()
authorizationStatus = locationManager.authorizationStatus
super.init()
locationManager.delegate = self
}
/* @MainActor */ func checkAuthorizationStatus() async -> CLAuthorizationStatus
{
let status = locationManager.authorizationStatus
if status == .notDetermined
{
return await withCheckedContinuation
{ continuation in
authorizationContinuation = continuation
locationManager.requestWhenInUseAuthorization()
}
}
else
{
authorizationStatus = status <=== WARNING
return status
}
}
}
extension Locator : CLLocationManagerDelegate
{
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager)
{
authorizationStatus = manager.authorizationStatus
authorizationContinuation?.resume(returning: authorizationStatus)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print(error)
self.error = error
location = nil
}
}
在没有生成整个类或checkAuthorizationStatus()
@MainActor
的情况下,我会收到以下运行时警告:
不允许从后台线程发布更改;确保从主线程发布值(通过receive(on:)等操作符)
在这种情况下以及一般情况下,选择使整个类成为@MainActor
还是只使需要它的函数/"部分"成为@MainActor
时,您会考虑什么?
编辑:为了满足那些投票结束这个问题的人,因为它似乎是基于观点:在上面的代码中,这两个选项在运行时有什么区别吗?
1条答案
按热度按时间k3bvogb11#
用户界面需要在
MainActor
上更新,否则您会收到“在后台发布更改警告”。如果class
的目的是更新用户界面,则应使用MainActor
Package 。