我正在使用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
的实体,其属性为firstName
,lastName
和address
。
我的问题是如何使用NSManagedObject
提取person
中的所有数据? (2个具有3个属性的对象)
答案 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
中使用它。