我正在尝试将属性从我发送的消息保存到我的核心数据 . 但每次我保存新消息时,它们都不会附加现有消息,它们只会覆盖整个实体 . 我希望你明白我的意思 .
我的代码看起来像这样,我的接收器是从另一个VC检索的:
var receivers: [String] = []
@IBAction func doneTapped(sender: AnyObject) {
for receiver in receivers{
var textMessage = PFObject(className:"textMessage")
textMessage["Receiver"] = receiver
textMessage["Message"] = messageOutl.text
textMessage.saveInBackgroundWithBlock {
(success: Bool!, error: NSError!) -> Void in
if (success != nil) {
self.errorOccurred = true
NSLog("Object created with id: \(textMessage.objectId)")
} else {
NSLog("%@", error)
}
}
}
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("MainTable", inManagedObjectContext: contxt)
var newMessage = SecondModel(entity: en!, insertIntoManagedObjectContext: contxt)
for rec in receivers{
newMessage.receiver = rec
newMessage.date = NSDate()
newMessage.messageType = typeOfMessage
contxt.save(nil)
}
}
任何关于如何解决这个或为什么会发生这种情况的建议将不胜感激 .
编辑:我改变了我的“en”和“newMessage”:
let en: AnyObject! = NSEntityDescription.insertNewObjectForEntityForName("MainTable", inManagedObjectContext: contxt)
var newMessage = SecondModel(entity: en! as NSEntityDescription, insertIntoManagedObjectContext: contxt)
但现在我在第二行得到“(lldb)”错误 .
编辑2:我解决了这个问题,摆脱了第二个for-loop,而是将“save-to-core-data”代码放在第一个for-loop中 . 我仍然不知道为什么第一个代码不应该工作 .
1 回答
要插入CoreData,您需要使用
当您创建实体时 .
然后你通常用这样的东西保存:
看起来你在做:
创建实体,但
entityForName:inManagedObjectContext:
类方法,根据documentation,"Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator."你不想 get 你坚持的对象;你想 create 一个对象并坚持下去 .
希望能帮助到你!