摆脱核心数据swift 3中的空条目

时间:2016-12-12 16:13:46

标签: core-data swift3 xcode8 ios10

我会向您展示我的模拟应用运行的图片:enter image description here

我需要摆脱那些空洞的条目。我会告诉你我的存储,清理和获取方法。

存储:

func createGetContext() -> NSManagedObjectContext{

        let appDelegate = (UIApplication.shared.delegate as? AppDelegate)

         return (appDelegate?.persistentContainer.viewContext)!

    }

    private func createMessageWithText(text: String, friend: Friend, minutesAgo: Double, context: NSManagedObjectContext) {

        //setting up the message as a Message() type and filling in the parameters
        let message = NSEntityDescription.insertNewObject(forEntityName: "Message", into: context) as! Message
        message.friend = friend
        message.text = text
        message.date = NSDate().addingTimeInterval(-minutesAgo * 60)

    }

    //setting up the data
    func setupData(){

        clearData()
        //batchDelete()

        let context = createGetContext()

        let adagio = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context) as! Friend
        adagio.name = "Adagio"
        adagio.profileImageName = "photo_adagio"


        let glaive = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context) as! Friend
        glaive.name = "Glaive"
        glaive.profileImageName = "photo_glaive"

        let ringo = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context) as! Friend
        ringo.name = "Ringo"
        ringo.profileImageName = "photo_ringo"

        let celeste = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context) as! Friend
        celeste.name = "Celeste"
        celeste.profileImageName = "photo_celeste"

        createMessageWithText(text: "This is boredom at its best!", friend: adagio, minutesAgo: 2, context: context)
        createMessageWithText(text: "Somebody! get a soda.", friend: adagio, minutesAgo: 3, context: context)
        createMessageWithText(text: "Im going to cut you into little pieces.", friend: adagio, minutesAgo: 1, context: context)
        createMessageWithText(text: "Eat axe, bitch!!", friend: glaive, minutesAgo: 4, context: context)
        createMessageWithText(text: "Anybody wants to be my pingpong ball?!", friend: glaive, minutesAgo: 0, context: context)
        createMessageWithText(text: "Drunk right now!", friend: ringo, minutesAgo: 2, context: context)
        createMessageWithText(text: "Stars and Boom!", friend: celeste, minutesAgo: 6, context: context)

        do {
            try context.save()
            print("Saved!!!!!")
        } catch let err {
            print(err)
        }

        getMessages()

    }

清算方法(我试过2次):

func clearData() {

        //create a fetch request, telling it about the entity
        let fetchRequestMessage: NSFetchRequest<Message> = Message.fetchRequest()

        let fetchRequestFriend: NSFetchRequest<Friend> = Friend.fetchRequest()

        do {
            //running the fetch request and adding to the array.
            friends = try createGetContext().fetch(fetchRequestFriend) as [Friend]

            for friend in friends! {
                //looping and deleting
                createGetContext().delete(friend)
            }

            //go get the results and add it to an Array to be deleted
            messages = try createGetContext().fetch(fetchRequestMessage) as [Message]

            for message in messages! {
                //loop through array and delete every message
                createGetContext().delete(message)

            }
            //have to save the context after deleting
            try (createGetContext().save())

        } catch {
            print("Error with request: \(error)")
        }

    }
    //delete the everything, (bug: does not display anything on the tableView if run)
    private func batchDelete() {

        let fetchRequestMessage: NSFetchRequest<Message> = Message.fetchRequest()

        let fetchRequestFriend: NSFetchRequest<Friend> = Friend.fetchRequest()

        let requestFriend = NSBatchDeleteRequest(fetchRequest: fetchRequestFriend as! NSFetchRequest<NSFetchRequestResult>)

        let requestMessage = NSBatchDeleteRequest(fetchRequest: fetchRequestMessage as! NSFetchRequest<NSFetchRequestResult>)

        do {

            try createGetContext().execute(requestFriend)
            try createGetContext().execute(requestMessage)


        } catch let err {

            print(err)
        }
    }

和获取方法:

//fetching the messages
    func getMessages () {

        if let friends = fetchFriends() {

            for friend in friends {
                print(friend.name!)


                //create a fetch request, telling it about the entity
                let fetchRequest: NSFetchRequest<Message> = Message.fetchRequest()
                //sort the array by time/date
                fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
                //filtering the pull with friend's name equal to friend.name!
                fetchRequest.predicate = NSPredicate(format: "friend.name = %@", friend.name!)
                //limit pull to 1 item
                fetchRequest.fetchLimit = 1

                do {
                    //go get the results and add to array for display
                    let fetchedMessages = try createGetContext().fetch(fetchRequest) as [Message]
                    //appending the messages into the message array
                    messages?.append(contentsOf: fetchedMessages)

                } catch {
                    print("Error with request: \(error)")
                }
                //sorting the messages array...throwing a nil...need to fix
//                messages?.sort(by: { $0.date?.compare($1.date as! Date) == ComparisonResult.orderedAscending })

            }
        }


    }

我认为这些条目来自失败的测试。正如您所看到的,我已经尝试清空实体,并尝试将它们拉入数组并逐个删除它们。没有用。帮帮我吧:)或者至少帮助弄清楚如何不在阵列中添加它们以便它们不会出现。提前谢谢!

1 个答案:

答案 0 :(得分:1)

经过无数次测试后,我在viewDidLoad中运行了batchDelete()方法,而不是在batchDelete()之后运行的setupData()方法中运行,这样就可以了。

这里的教训是,不要等待答案。在等待答案时总是试着跋涉。