2016-11-11 54 views
2

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

谢谢。

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

回答

0

我不太肯定我是否正确理解你,但如果你只是想尝试从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数据的数组,你可以访问数据的name属性索引index。现在你只需要创建一些遍历这个数组的循环,然后查找display.text = controller.fetchedObjects?[index].namedisplay标签显示的数据(不要忘记先调用attemptFetch函数)。