我正在使用核心数据。有两个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 个属性)
最佳答案
试试这个代码
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
中使用它。
关于ios - 访问 NSManagedObject 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34081169/