1

Here is a function (very useful to insert information into Core Data) that has been working for quite a long time. Since I moved to Swift 3.0, it is having trouble, crashing on the first line. Did I miss something?

func insertObject<T:NSManagedObject>(_ entity:T.Type, dico:NSDictionary, notification:String!) -> NSManagedObject? {
    let entityName = entity.entityName
    let newItem = NSEntityDescription.insertNewObject(forEntityName: entityName, into:managedObjectContext!) as! T

    for (key, value) in dico {
        if let value:AnyObject = value as AnyObject? {
            (newItem as NSManagedObject).setValue(value, forKey: key as! String)
        }
    }

    do {try managedObjectContext!.save()
        // We may send a notification:
        if (notification != nil)
        {NotificationCenter.default.post(name: Notification.Name(rawValue: notification), object: nil)}
    } catch let error as NSError {print(error)}

    return newItem
}

Beside I get this error in the debugger console:

fatal error: Index out of range

And I can see the following, along with the assembly code:

    0x1007811f8 <+116>: bl     0x100674b80               ; function signature specialization <preserving fragile attribute, Arg[1] = [Closure Propagated : reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> ()]> of generic specialization <preserving fragile attribute, ()> of Swift.StaticString.withUTF8Buffer <A> ((Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A
->  0x1007811fc <+120>: brk    #0x1
Michel
  • 10,303
  • 17
  • 82
  • 179

1 Answers1

0

if you want to save data in core database you can use the below code.

step 1: Declare this 3 variable as mention below:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

var managedContext:NSManagedObjectContext!

var entity:NSEntityDescription!

step 2: you can put this code in viewdidlode() or in that function that you use for save data.

managedContext = appDelegate.persistentContainer.viewContext

entity = NSEntityDescription.entity(forEntityName: "Student", in: managedContext)

let storeStudent = NSManagedObject.init(entity: entity, insertInto: managedContext)

        storeStudent.setValue(1, forKey: "rollno")
        storeStudent.setValue("Anil", forKey: "name")
        storeStudent.setValue("abc street", forKey: "address")

        do {
            try managedContext.save()
        } catch let error as Error! {
            print(error.localizedDescription)
        }
nishee
  • 141
  • 7