我在我的app delegate中有以下代码作为在我的其他viewControllers中使用CoreData的快捷方式:
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)
但是,我现在收到错误消息:
"从后台线程调用UI API"和"UIApplication.delegate必须仅从主线程使用".
当我的应用程序在后台时,我正在使用CoreData,但这是我第一次看到此错误消息.有谁知道这里发生了什么?
更新:我试图在appDelegate类本身内移动它,并使用以下代码 -
let dispatch = DispatchQueue.main.async {
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
}
Run Code Online (Sandbox Code Playgroud)
现在,我无法再访问外部的广告和上下文变量AppDelegate.有什么我想念的吗?
现在,我正在尝试使用Git中的一个名为Insomnia的类来防止设备在充电时锁定.如果你好奇的话,这个项目就在这里.对于示例代码,它让我这样做:
final class AppDelegate: UIResponder, UIApplicationDelegate {
private let insomnia = Insomnia(mode: .whenCharging)
//app delegate code
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它已声明AppDelegate为final使得insomnia变量未被释放,这将阻止它工作.但是,我不确定,这是不好的做法宣布我AppDelegate的final?或者这会导致我的应用程序出现问题吗?如果这是不好的做法,有没有更好的方法来确保insomnia不被解除分配?
我有一个 segue,它是通过一个按钮触发的,该按钮在当前上下文中以模态方式显示另一个视图控制器。我正在使用自定义类来自定义过渡,这是这样的:
class ShowAnimator: NSObject {
}
extension ShowAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to) else {
return
}
let containerView = transitionContext.containerView
containerView.insertSubview(fromVC.view, belowSubview: toVC.view)
let toFrame = transitionContext.finalFrame(for: toVC)
let screenBounds = UIScreen.main.bounds
let bottomLeftCorner = CGPoint(x: screenBounds.width, y: 0)
let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size)
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: {
fromVC.view.frame = finalFrame
}, …Run Code Online (Sandbox Code Playgroud)