1

这是一个已经工作了很长时间的函数(对于向 Core Data 插入信息非常有用)。自从我搬到 Swift 3.0 之后,它就遇到了麻烦,在第一行就崩溃了。我错过了什么?

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
}

除此之外,我在调试器控制台中收到此错误:

fatal error: Index out of range

我可以看到以下内容以及汇编代码:

    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
4

1 回答 1

0

如果要将数据保存在核心数据库中,可以使用以下代码。

第 1 步:声明这 3 个变量,如下所述:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

var managedContext:NSManagedObjectContext!

var entity:NSEntityDescription!

第 2 步:您可以将此代码放入 viewdidlode() 或用于保存数据的函数中。

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)
        }
于 2017-07-14T07:25:35.540 回答