简体   繁体   中英

How to store data in Core data from Data model in iOS and get in the format of data model

I want to store data as data model in iOS. I am trying this but it is not working.

My data model class

class FileSaveModel: NSManagedObject {
    @NSManaged var id: String
    @NSManaged var name: String
    @NSManaged var path: String
    @NSManaged var time: String
    @NSManaged var type: String
    @NSManaged var uid: String

    // TODO: - Need to get the use of this
   // lazy var uidd: NSManagedObjectID = NSManagedObjectID()

    override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
    }

    init(name:String, path: String, contentType: ContentType, entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)

        self.path = path
        self.name = name
        self.type = contentType.rawValue
        self.time = "\(NSDate())"
        self.uid = "56"
        self.id = "789"
    }
}

Saving like this

func save(name: String, path: String, type: ContentType, modelContent: ModelTest)  {

        guard let entity = self.entityWith(name: entityName) else {
            return
        }

When i try to save with this it saves

//let modelFile = FileSaveModel(name: name, path: path, contentType: //type, entity: entity, insertInto: appDelegate.context())

But this crahses with error "cannot cast NSManagedObject to FileSaveModel"

        let model = NSEntityDescription.insertNewObject(forEntityName: entityName, into: appDelegate.context()) as! FileSaveModel

        model.name = name
        model.path = path
        model.type = type.rawValue

        save(model: model, modelContent: modelContent)
    }

    func save(model: FileSaveModel, modelContent: ModelTest) {

        do {
            try appDelegate.context().save()
            print("Save successful")
        } catch {
            fatalError("Failure to save context: \(error)")
        }
    }

Getting data like this but not returning the FileSaveModel array only returning the NSManagedObject array

func fetchAllModels() {
        let fetchItems = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)

        do {

            let fetchedItems = try appDelegate.context().fetch(fetchItems) as! [FileSaveModel]

            if fetchedItems.count>0 {
                print(fetchedItems[0].name)
            }

        } catch {
            fatalError("Failed to fetch: \(error)")
        }
    }

If I understand your question.

Select xcdatamodeld -> Your Entity -> Data Module Inspector -> Module

If it is current product module change it to Global namespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM