首页 > 解决方案 > 将 uiimageview 保存为 coredata 作为二进制数据 swift (5)

问题描述

我正在尝试将 imageview 作为图像保存到核心数据中的二进制数据中。我的代码不起作用。它有一个编译错误。在视图控制器中,它没有注册 cdHandler。我想要做的就是将 imaveview 保存为核心数据模型中的二进制数据。我有 2 个类,一个应用程序委托和一个视图控制器。

类视图控制器

    import UIKit
import CoreData

class ViewController: UIViewController {
var canVasView = UIImageView()
@objc func hhh() {
    let photo = self.canVasView.image
    let data = photo!.pngData()

    if cdHandler.saveObject(pic:  data!){
    }
}
}

应用程序代表

  import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


     lazy var persistentContainer: NSPersistentContainer = {
         /*
          The persistent container for the application. This implementation
          creates and returns a container, having loaded the store for the
          application to it. This property is optional since there are legitimate
          error conditions that could cause the creation of the store to fail.
          */
         let container = NSPersistentContainer(name: "Model")
         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
             if let error = error as NSError? {
                 // Replace this implementation with code to handle the error appropriately.
                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
class cdHandler: NSObject {

    private class func getContext() -> NSManagedObjectContext {
        let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
        return appdeleagetzz.persistentContainer.viewContext
    }
    class func saveObject(pic: Data, userName: String) -> Bool {
        let context = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
        let managedObject = NSManagedObject(entity: entity!, insertInto: context)
        managedObject.setValue(pic, forKey:"pic")
        managedObject.setValue(userName, forKey:"userName")
        do {
            try context.save()
            return true

        } catch {
            return false

        }
    }
    class func deletObject(user: User) -> Bool {
        let context = getContext()
        context.delete(user)

        do {
            try context.save()
            return true
        } catch {
            return false

        }
    }

    class func fetchObject() -> [User]? {

        do {
            let context = getContext()
            return try context.fetch(User.fetchRequest())
        } catch {
            return [User]()
        }
    }

}
}

在此处输入图像描述

标签: core-dataimageviewappdelegatebinary-dataswift5

解决方案


错误消息,*“AppDelegate”类型的值没有名为“persistentContainer”的成员,解释了问题。事实上,当我查看您的AppDelegate类的代码时,我可以确认它没有名为“persistentContainer”的成员。(如果我没看错的话,文件中的最后两行是大括号。第一行关闭你的cdHandler嵌套类,第二行关闭你的AppDelegate类。)

做以下练习。在 Xcode 中,单击菜单:File > New Project并选择iOSApplicationSingle View App。将您的新项目命名为 Junk。打开核心数据复选框。单击按钮创建。完成后,查看 Xcode 创建的 AppDelegate.swift,在AppDelegate类中,您会看到它包含 8 个函数 ( func)。第 7 个是lazy var persistentContainer. 啊哈!编译器告诉您,您可能不应该删除这 8 个函数,persistentContainer尤其是.

您应该将该persistentContainer功能从该垃圾项目复制到AppDelegate您实际项目中的类中。或者,为了避免未来的麻烦,也可以考虑复制其他 7 个函数中的大部分。正如你所看到的,他们中的大多数除了提供对初学者有用的解释之外什么都不做。完成复制后,关闭Junk项目。(我在一个典型的一周内多次用一个新的垃圾项目覆盖我的垃圾项目,尤其是在回答 StackOverflow 问题时。)

这应该可以解决这个特定的错误并回答这个问题。继续下一期。:)

回复您仍然收到cdHandler 错误的评论

没有其他事情可做,我认为您所指的错误是仍然在您的屏幕截图中的编译器错误换句话说,您是说添加persistentContainer定义并没有使它变得更好。

好吧,它对我有用。请用以下代码替换AppDelegate.swift类中的所有代码,构建并运行它...</p>

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AppDelegate.cdHandler.testGetContext()
        return true
    }

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "Junk")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    class cdHandler: NSObject {

        private class func getContext() -> NSManagedObjectContext {
            let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
            return appdeleagetzz.persistentContainer.viewContext
        }

        class func testGetContext() {
            let context = getContext()
            print("getContext() succeeded, got \(context)")
        }

        class func saveObject(pic: Data, userName: String) -> Bool {
            let context = getContext()
            let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
            let managedObject = NSManagedObject(entity: entity!, insertInto: context)
            managedObject.setValue(pic, forKey:"pic")
            managedObject.setValue(userName, forKey:"userName")
            do {
                try context.save()
                return true

            } catch {
                return false

            }
        }
        class func deletObject(user: NSManagedObject) -> Bool {
            let context = getContext()
            context.delete(user)

            do {
                try context.save()
                return true
            } catch {
                return false

            }
        }

    }
}

你会看到编译没有错误。此外,它运行并且 AppDelegate.cdhandler.getContext() 方法有效。如您所见,在AppDelegate.application(application:didFinishLaunchingWithOptions:), I have added a call to a new method which I defined later,AppDelegate.cdHandler.testGetContext()` 中。它完美地工作。

你现在得到一个不同的错误吗?如果是这样,您需要指定它是构建错误还是运行错误。无论哪种情况,请将错误文本复制并粘贴到您的问题中,并告诉我们错误发生的位置。


推荐阅读