以下の私の迅速なコードは、2 つの画像リテラルを受け取り、コア データに保存します。私がしたいのは、 func fetch で、コアデータに保存されている属性の数を dubgg 領域に出力することだけです。したがって、debugg セクションには、debugg セクションに 2 つの項目が保存されていると表示されます。
import UIKit
import CoreData
class ViewController: UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var piczy = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
let newUser = User(context: context)
let newUser2 = User(context: context)
newUser.pic = #imageLiteral(resourceName: "Jessica").jpegData(compressionQuality: 0.9) as NSObject?
newUser2.pic = #imageLiteral(resourceName: "Jessica").jpegData(compressionQuality: 0.9) as NSObject?
save()
}
func save() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do {
let jake = try context.count(for: fetchRequest)
print(jake)
} catch let error as NSError {
print("Could not fetch \(error) ")
}
}