清除数据的替代方法以避免在coreData中重复

时间:2016-08-13 18:46:41

标签: ios swift core-data

我正在将数据保存到Firebase的核心数据中,但每次关闭应用并再次打开时,数据都会重复。

所以我决定清除Data,然后重新填充我的CoreData。有更好,更有效的方法吗?

喜欢更新数据,如果它已经改变了什么?

(忽略setupdata中的图形请求,我只是将它用作完成处理程序)

func setupData() {


    let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    context.persistentStoreCoordinator = CDHelper.sharedInstance.coordinator

    clearData()
    getFriendId(context)


    let request: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id"], HTTPMethod: "GET")
    request.startWithCompletionHandler({(connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
        do {
            try context.save()
        }
        catch {
        }
        self.loadData(context)
    })
}
func clearData() {

    let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    context.persistentStoreCoordinator = CDHelper.sharedInstance.coordinator

        do {

            let entityNames = ["Friend", "Messages"]

            for entityName in entityNames {
                let fetchRequest = NSFetchRequest(entityName: entityName)

                let objects = try(context.executeFetchRequest(fetchRequest)) as? [NSManagedObject]

                for object in objects! {
                    context.deleteObject(object)
                }
            }

            try(context.save())


        } catch let err {
            print(err)
        }


}
func getFriendIdandMessagesFromFirebase(context: NSManagedObjectContext) {
    let ref = FIRDatabase.database().reference().child("user-messages").child(userdefaults.objectForKey("FBid") as! String)
    ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in

        let friendID = snapshot.key
        let friend = NSEntityDescription.insertNewObjectForEntityForName("Friend", inManagedObjectContext: context) as! Friend
        friend.id = friendID

    let ref2 = FIRDatabase.database().reference().child("user-messages").child(self.userdefaults.objectForKey("FBid") as! String).child(friendID)
        ref2.observeEventType(.ChildAdded, withBlock: {(snapshot2) in
            let messageId = snapshot2.key

            let messagesRef = FIRDatabase.database().reference().child("messages").child(messageId)
            messagesRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in



                let dictionary = snapshot.value as! [NSObject: AnyObject]

                let timestamp = dictionary["timestamp"] as! NSNumber
                let doubleTimestamp = Double(timestamp)

                let date = NSDate(timeIntervalSinceReferenceDate: (doubleTimestamp))

                self.createMessageWithText(dictionary["text"]! as! String, friend: friend, context: context, date: date)

            })})})
}

0 个答案:

没有答案