2016-11-11 63 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函數)。