【问题标题】:Accessing NSManagedObject Data访问 NSManagedObject 数据
【发布时间】:2015-12-04 04:57:30
【问题描述】:

我正在使用 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 个属性的对象)

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    试试这个代码

          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 中使用它。

    【讨论】:

    • 但是,在我的应用程序中,用户可以直接访问SecondViewController,而无需先访问FirstViewController。那也行吗?
    • 不,在这种情况下,它将不起作用,如果 fetchData 写入 firstViewController 则用户必须通过它。如果你想让 fetchData 独立于 FirstViewController,那么将它移动到 SecondViewController 或像“AppDelegate”这样的集中式对象。
    • 我的应用程序的结构是FirstViewController 用于存储,而SecondViewController 用于访问。用户可以退出应用程序,启动后立即访问SecondViewController。根据您的说法,我可以将我的 fetchData() 放在带有 NSManaged 类的 SecondViewController 中,它应该可以工作吗?
    • 是的,它肯定会与您的应用程序流一起使用,因为访问数据与存储机制无关,它们彼此独立,将 fetchData 放置在 SecondViewController 中将是一个好方法。如果对您有帮助,请采纳答案。
    • Yes 将对其进行测试并接受您的回答。但是,我需要先弄清楚如何做我的 NSManaged 课程。抱歉,我是 swift 新手,我已经创建了我的 NSManaged 子类,但是在那个子类中,要在那里创建 String 属性吗?
    猜你喜欢
    • 1970-01-01
    • 2012-09-14
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多