gpt4 book ai didi

swift - 使用核心数据中的索引来获取特定的二进制数据

转载 作者:行者123 更新时间:2023-11-30 10:27:05 25 4
gpt4 key购买 nike

下面的 swift 代码将 2 个单独的图像保存到核心数据中。我想要做的是,当用户在文本字段中输入 1 时,输入核心数据的第一张图像将出现在 imaegview 图片上。如果输入 2,第二张图像将出现在 ImageView 上。我的代码基于使用字符串而不是二进制数据。我在 pic.image = user.image 处收到编译错误,指出无法分配“数据”类型的值?输入“UIImage?”。 https://github.com/redrock34/be

enter image description here

 import UIKit
import CoreData


class ViewController: UIViewController,UITextFieldDelegate {


@IBOutlet var labelName : UILabel!
@IBOutlet var enterT : UITextField!
@IBOutlet var pic : UIImageView!
lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


var dx = [UIImage]()
var names = [String]()

override func viewDidLoad() {
super.viewDidLoad()


enterT.delegate = self

pic.backgroundColor = .cyan


guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Users", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
let item2 = NSManagedObject(entity: entity, insertInto: managedContext)
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

let vex = UIImage(named: "on.jpg")?.pngData()
if let data = vex{
item.setValue(data, forKey: "image")

}




let vex2 = UIImage(named: "house.jpg")?.pngData()
if let data2 = vex2{
item2.setValue(data2, forKey: "image")
}




do {
let result = try? managedContext.fetch(fetch) as? [Users]
print("Queen",result?.count)
try? managedContext.save()



}
catch {
print("Could not save")
}


}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

guard let text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), let index = Int(text) else { //here....
// display an alert about invalid text
return true
}
save(at: index )
return true
}

func save(at index : Int) {
let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
fetchRequest.predicate = NSPredicate(format: "idx == %d", Int32(index))
do {
if let user = try context.fetch(fetchRequest).first {
pic.image = user.image
}
} catch {
print("Could not fetch \(error) ")
}
return
}

@IBAction func add(){


fetch()
}

func fetch()
{



for i in 0..<dx.count {
let newUser = Users(context: context)
newUser.username = names[i]
newUser.idx = Int32(i + 1)


}
print("Storing Data..")
do {
try context.save()
} catch {
print("Storing data Failed", error)
}
return
}


}

最佳答案

您需要将 Data 类型的图像转换为 UIImage,如下所示。

UIImage(data: user.image ?? Data())

关于swift - 使用核心数据中的索引来获取特定的二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59959580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com