将uiimageview保存为coredata作为二进制数据swift(5)

时间:2019-05-29 02:02:29

标签: core-data imageview appdelegate binary-data swift5

我正在尝试将imageview作为图像保存为核心数据中的二进制数据。我的代码无法正常工作。它有一个编译错误。在View Controller中,它不需要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]()
        }
    }

}
}

enter image description here

1 个答案:

答案 0 :(得分:0)

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

进行以下锻炼。在Xcode中,单击菜单:文件> 新项目,然后选择 iOS Application Single查看应用。将您的新项目命名为 Junk 。开启核心数据复选框。点击按钮创建。完成后,查看Xcode创建的AppDelegate.swift,在AppDelegate类中,您看到它包含8个函数(func)。第七位是lazy var persistentContainer。啊哈!编译器告诉您您可能不应该删除这8个函数,尤其是persistentContainer

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

那应该解决此特定错误并回答此问题。继续下一期。 :)

回应评论说您仍然收到cdHandler错误

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

嗯,它对我有用。请用以下代码替换您的 AppDelegate.swift 类中的所有代码,并生成并运行…

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()`中。效果很好。

您现在遇到其他错误了吗?如果是这样,则需要指定它是“生成”还是“运行”错误。无论哪种情况,都将错误文本复制并粘贴到您的问题中,然后告诉我们发生错误的地方。