使用swift在coredata中的一对一关系

时间:2015-04-24 05:23:36

标签: swift core-data nsset

我是swift的新手,并试图与我的收据发票coredata保持一对一的关系。

我无法使用NSSet设置关系。以下是我的代码:

func addReceipt(receipt: NSMutableDictionary){

    let managedContext = appDelegate.managedObjectContext!
    let entityReceipt = NSEntityDescription.entityForName("Receipt", inManagedObjectContext: managedContext)

    let newReceipt = NSManagedObject(entity: entityReceipt!, insertIntoManagedObjectContext: managedContext)

    if let invoice = addInvoic(receipt){
        newReceipt.setValue(NSSet(object: invoice), forKey: "invoice")
    }
}

func addInvoic(receipt: NSMutableDictionary) -> NSManagedObject!{

    let managedContext = appDelegate.managedObjectContext!
    let entityInvoice = NSEntityDescription.entityForName("Invoice", inManagedObjectContext: managedContext)
    let newInvoice = NSManagedObject(entity: entityInvoice!, insertIntoManagedObjectContext: managedContext)

    newInvoice.setValue(receipt.valueForKey("companyName"), forKey: "companyName")
    newInvoice.setValue(receipt.valueForKey("address"), forKey: "address")
    newInvoice.setValue(receipt.valueForKey("merchant"), forKey: "merchant")


    var returnObj: NSManagedObject!
    if (saveObject()){
        returnObj = newInvoice
    }
    return returnObj
} 

此方法成功保存发票并返回保存NSManagedObject。但是,当我尝试设置该对象时,它会给我以下错误

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSetI managedObjectContext]: unrecognized selector sent to instance 0x16ee0960'
*** First throw call stack:(0x24ad35a7 0x327f1c77 0x24ad8a6d 0x24ad6949 0x24a07b68 0x247fadf1 0x247fa09d 0x24819077 0x2481de37 0x90360 0x9d3b0 0x871dc 0x85130 0x8a48c 0x934a4 0x84c2c 0x84db4 0x28008707 0x280086a9 0x27ff343d 0x280080d9 0x28007db3 0x280016c1 0x27fd7fbd 0x2824bbb5 0x27fd6a07 0x24a9a237 0x24a9964b 0x24a97cc9 0x249e4b51 0x249e4963 0x2bf4a1a9 0x28036c91 0x5a044 0x32d9aaaf)
libc++abi.dylib: terminating with uncaught exception of type NSException

对于Objective-C,我将其实现为

[NSSet setWithObject:invoice]

我不知道我在哪里弄错了。请帮忙。任何帮助都会受到赞赏。

提前致谢

0 个答案:

没有答案