访问NSManagedObject数据

时间:2015-12-04 04:57:31

标签: ios swift core-data

我正在使用Core Data。我的ViewController我使用SecondViewController方法有两个fetchData(),如下所示,用于获取我存储在FirstViewController中的数据。

 func fetchData() {
            var person = [NSManagedObject]()
            let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext = appDel.managedObjectContext

            let fetchRequest = NSFetchRequest(entityName: "People")

            do{
                let results = try managedContext.executeFetchRequest(fetchRequest)
                person = results as! [NSManagedObject]
            } catch let error as NSError {
                print("Could not fetch data \(error)")
            }

            print(person)
    }

通过打印counters我已经确认有2 data: <fault>我已经了解到我的数据实际存在,但它是一种节省内存的技术。

对于我的核心数据,我有一个名为People的实体,其属性为firstNamelastNameaddress

我的问题是如何使用NSManagedObject提取person中的所有数据? (2个具有3个属性的对象)

1 个答案:

答案 0 :(得分:0)

试试此代码

      func fetchData() {

           var peoples  = [People]() // Where People = your NSManaged Class
           var fetchRequest = NSFetchRequest(entityName: "People")
           let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
           let context = appDel.managedObjectContext

           do
           {    
             peoples = try context.executeFetchRequest(fetchRequest) as! [People]
           } 
           catch let error as NSError
           {
             print("Could not fetch data \(error)")
           }
           // Then you can use your propertys.
           for people in peoples {
             print("FirstName: \(people.firstName)  LastName: \(people.lastName)   Address: \(people.address)")   
           }

     }

最好从fetchData方法返回对象数组,并在secondViewController中使用它。