使用核心数据索引从核心数据中获取特定项目

Use core data index to fetch a specific item from core data

下面我的 swift 代码在加载时将 3 个项目放置在名为 "UserName" 的核心数据实体中。当用户在文本字段中输入数字时,我希望标签 labelName 显示它。因此,当用户输入 1 时,标签应显示 jessica biel,因为 Jesical Biel 是输入的名字。有人在下面提出了解决这个问题的建议。我不知道具体怎么做 this.I 在下面添加了一个 gif。

将输入的数字转换为整数。如果成功,将整数传递给 joke 并获取与 idx 属性匹配的记录。

https://github.com/redrock34/index-fetch

导入 UIKit 导入核心数据

  class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var labelName : UILabel!
@IBOutlet var enterT : UITextField!

lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

override func viewDidLoad() {
    super.viewDidLoad()

    openDatabse()
    fetchData()
    enterT.delegate = self


}

func textFieldDidEndEditing(_ textField: UITextField) {
    guard let index = Int(textField.text!) else {
        // display an alert about invalid text
        return
    }
    joke(at: index - 1)
}

func joke(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 {
            labelName.text = user.username
        }
    } catch {
        print("Could not fetch \(error) ")
    }
}
func openDatabse()
{
    let names = ["kim kardashian", "jessica biel", "Hailey Rienhart"]
    for i in 0..<names.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)
    }
}
func fetchData()
{
    print("Fetching Data..")
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            let userName = data.value(forKey: "username") as! String

            print("User Name is : "+userName)
        }
    } catch {
        print("Fetching data Failed")
    }
}}

当然,您必须为 idx 属性赋值,并且必须将获取的结果赋值给标签。

先替换

let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instanc
var context:NSManagedObjectContext!

lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

然后将openDatabsesaveData都替换为

func openDatabse()
{
    let names = ["kim kardashian", "jessica biel", "Hailey Rienhart"]
    for i in 0..<names.count {
        let newUser = Users(context: context)
        newUser.name = names[i]
        newUser.idx = Int32(i + 1)
    }
    print("Storing Data..")
    do {
        try context.save()
    } catch {
        print("Storing data Failed", error)
    }
}

最后在joke中加一行显示值

func joke(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 {
            labelName.text = user.username
        }
    } catch {
        print("Could not fetch \(error) ")
    }
}

它创建记录并分配适当的索引。然后在文本字段中输入数字应该可以。

但是 - 再一次 - 在每次启动应用程序时,都会再次插入 3 条具有相同名称和索引的记录。请注意这一点!