在类型为'AppDelegate *'的对象上找不到'managedObjectContext'属性。

问题描述 投票:0回答:1

我正在更新Objective-C中的一些代码,需要从Swift 3转换到一个新的版本。我遇到了一个错误,我不知道该怎么办。错误的代码是

AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
_managedObjectContext = appDelegate.managedObjectContext;

AppDelegate的managedObjectContext部分为

lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

我得到的错误是 Property 'managedObjectContext' not found on object of type 'AppDelegate *'. 我不懂Objective-C,我只是需要更新一些资源文件,应用的其他部分就围绕着这些资源文件落到了实处,所以我真的不知道如何解决这个问题。有什么技巧吗?这一行在整个应用程序中重复了好几次。

objective-c swift
1个回答
1
投票

如果你的桥接头设置正确,那么就可以让属性为 @objc 如下图所示

@objc lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()
© www.soinside.com 2019 - 2024. All rights reserved.