Swift在标签上显示核心数据

时间:2016-11-11 22:56:34

标签: swift core-data label schema

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

感谢。

这是我的插入功能的代码;将它放在名为' 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.
  }
}

1 个答案:

答案 0 :(得分:0)

我不太确定我是否正确理解你,但如果你只是想尝试从CoreData获取数据并将其显示在标签上,你可以这样做:
确保导入include。将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属性1}}。现在你只需创建一些迭代遍历此数组的循环,并使用name查找要显示到index标签的数据(不要忘记调用{{1}首先是函数。)