core-data - 将 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]()
}
}
}
}
解决方案
错误消息,*“AppDelegate”类型的值没有名为“persistentContainer”的成员,解释了问题。事实上,当我查看您的AppDelegate
类的代码时,我可以确认它没有名为“persistentContainer”的成员。(如果我没看错的话,文件中的最后两行是大括号。第一行关闭你的cdHandler
嵌套类,第二行关闭你的AppDelegate
类。)
做以下练习。在 Xcode 中,单击菜单:File > New Project并选择iOS、Application和Single 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()` 中。它完美地工作。
你现在得到一个不同的错误吗?如果是这样,您需要指定它是构建错误还是运行错误。无论哪种情况,请将错误文本复制并粘贴到您的问题中,并告诉我们错误发生的位置。
推荐阅读
- asp.net - 在配置服务中获取服务实例(不是通过 services.BuildServiceProvider())
- r - 删除警告消息“在缓存中发现多个类“tbl_df”;使用第一个,来自命名空间 'tibble' 也由 'memisc' 定义
- node.js - 将 ghost CMS 安装到 AWS Elastic Beanstalk Node js 应用程序中
- ios - 如何判断objective-c中我的文件系统上有一个有效的pdf文件?
- arrays - 代码在使用指针时产生额外的一行并且不读取第一个字符数组
- java - nextInt 对这段代码中的 Scanner 类做了什么?
- logback - Logback:谨慎模式下基于大小的文件轮换
- ios - 无法在 Expo CLI 模拟器上运行 React Native App
- mysql - MySQL-在 SELECT 语句中创建重复的结果
- rust - 以数字开头的值的约定