【问题标题】:Swift display core-data on a labelSwift 在标签上显示核心数据
【发布时间】:2017-03-26 05:52:51
【问题描述】:

我想知道当我在标签上按“显示”时,如何让我的应用程序使用核心数据来保存用户数据以打印存储的数据(最好是字符串)。

谢谢。

这是我插入函数的代码;将它放在名为“display”的标签上会是什么样子?

    @IBAction func insertStudent(_ sender: AnyObject) {
    let context = getContext()
    let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts", in: context)

    let contact = NSManagedObject(entity: entityDescription!, insertInto: context) as! Contacts

    contact.name = name.text
    contact.address1 = address1.text
    contact.address2 = address2.text
    contact.city = city.text
    contact.grade = grade.text
    contact.state = state.text
    contact.zip = zip.text

    var error: NSError?

    //save the object
    do {
        try context.save()
        status.text = ("saved!")
    } catch let error as NSError  {
        status.text = ("Could not save \(error), \(error.userInfo)")
    } catch {

    }

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}

【问题讨论】:

    标签: swift core-data label schema


    【解决方案1】:

    我不太确定我是否正确理解了您,但如果您只是想尝试从 CoreData 获取数据并将其显示在标签上,您可以执行以下操作:
    确保已导入 CoreData。将NSFetchedResultsControllerDelegate 委托添加到您的类并创建一个全局变量var controller: NSFetchedResultsController<Contacts>!。 然后创建一个尝试(!)获取数据的函数:

    func attemptFetch() {
        let context = getContext()
        let fetchRequest: NSFetchRequest<Contacts> = Contacts.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    
        let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    
        controller.delegate = self
        self.controller = controller
    
        do {
            try controller.performFetch()
        } catch {
            let error = error as NSError
            print("\(error)")
        }
    }
    

    controller.fetchedObjects 现在拥有一个数组,其中包含来自Contacts 实体的所有数据,并且使用controller.fetchedObjects?[index].name,您可以访问索引index 处数据的name 属性。现在您只需要创建某种循环,该循环遍历此数组并查找要使用display.text = controller.fetchedObjects?[index].name 显示到您的display 标签的数据(不要忘记先调用attemptFetch 函数)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多