关于ios:使用Core Data和Parse的应用程序的体系结构

Architecture of an app using Core Data and Parse

我努力构建一个"待办事项"应用程序,该应用程序将从Parse下载活动,并用Core Data保存活动,然后将其显示在Apple Watch上。我想问一下这是否是一种或多或少的正确方法:

  • 在viewWillLoad中,我们检查是否存在Internet连接:

    • 如果为TRUE,我们将遍历核心数据中的活动,并将其与Parse中的活动进行比较

      • 如果他们比较,我们什么也不做,并使用核心数据中的信息准备单元格
      • 如果不进行比较,我们会将其添加到核心数据中并准备单元格
    • 如果为FALSE,我们将使用来自Core Data的信息来准备单元格
  • 我正在尝试实现自己的方式,但是遇到了问题。从解析中获取的数据仅在应用程序的第二次启动时显示。不要同时获取和显示。
    我的财产

    1
    2
    3
    4
    var medicines : [Medicine] = [Medicine]()
    var frc :NSFetchedResultsController!
    var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let fetchRequest = NSFetchRequest(entityName:"Medicine")

    我获取数据的方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    // MARK: - Fetching
    func fetchFromParse() {

        let entity = NSEntityDescription.entityForName("Medicine", inManagedObjectContext: context)

        let query = PFQuery(className:"Medicine")
        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            if error == nil {
                for object in objects! {
                    let medicine = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: self.context)
                    if let  name = object["medicineName"] as? String,
                            amount = object["amountQuantity"] as? String {
                        //save to  Core Data
                        medicine.setValue(name, forKey:"name")
                        medicine.setValue(amount, forKey:"amount")


                        do {
                            try self.context.save()

                        } catch let error as NSError {
                            print("Could not save \\(error), \\(error.userInfo)")
                        }
                    }
                }
            }
        }
    }


    func fetchFromCoreData() {

        do {
            let results = try context.executeFetchRequest(fetchRequest)
            medicines = results  as! [Medicine]
        } catch let error as NSError {
            print("Could not fetch \\(error), \\(error.userInfo)")
        }


    }

    我在viewWillAppear中称它们为

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    if Reachability.isConnectedToNetwork() {
            //fetching data from Parse

            fetchFromParse()
            fetchFromCoreData()

        } else {
            //fetching data from Core data
            fetchFromCoreData()
            logOutButton.enabled = false

        }


    一种更好的方法是设置一个后台任务,以使用Parse获取数据并将新条目粘贴到核心数据存储中,并在检测到新项时刷新主线程上的表。