Copy and paste the coredata object in my project iOS swift

 Problem:

I want to copy my coredata object into cache and paste it somewhere in my project.How can i achieve that?

Solution:

You have to achieve that by using userdefaults in your project.But you cannot save the entire object in the defaults.So you have to store the coredata object ID in the defaults.

While paste fetch the object based on coredata id and then paste it somewhere.

    // MARK: -  copy and paste the object

    func setCopyMyObj(valuemyObject) {

        self.userDefaults.set(value.objectID.uriRepresentation().absoluteStringforKey"myobj")

            self.saveValue()

    }

    

    func removeCopyObj() {

      self.userDefaults.removeObject(forKey"myobj")

      self.saveValue()

    }

    

    func getCopyObj()-> myObject? {

        guard let objID = UserDefaults.standard.string(forKey"myobj"else {

            return nil

        }

        let context = getContext()

        let fetchRequest: NSFetchRequest< myObject > = myObject.fetchRequest()

        fetchRequest.predicate = NSPredicate(format"id == %@", objID)

        do {

            let searchResults = try  context.fetch(fetchRequest)

            for eve in searchResults as [NSManagedObject] {

                return eve asmyObject

            }

        } catch {

            return nil

        }

        return nil

    }


Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift