我制作了一个使用核心数据的应用。我做了一个函数,它将1或2个值/写入数据保存到核心数据中。这是以下方法:
func saveName(name: String) {
let myDate:NSDate = NSDate()
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject
if markCell == true {
newManagedObject.setValue(name, forKey: "markedCell")
markCell = false
}
else {
newManagedObject.setValue(name, forKey: "name")
newManagedObject.setValue(myDate, forKey: "datum")
}
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
abort()
}
}
如果cellForRowAtIndexPath
,则会在markCell == true
函数中发生崩溃。如果markCell == false
(步入else
),所有工作都会完美。
如果我运行此功能:
func saveName(name: String) {
let myDate:NSDate = NSDate()
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject
newManagedObject.setValue(name, forKey: "markedCell")
markCell = false
newManagedObject.setValue(name, forKey: "name")
newManagedObject.setValue(myDate, forKey: "datum")
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
abort()
}
}
没有发生崩溃但是我还向markedCell
添加了一个值。我只想在markedCell
中添加一个值,如果bool设置为true(用户按下按钮 - > bool将设置为true
并且func saveName
将被调用)。
从核心数据加载数据(创建UITableViewCell):
//Get task
let context = self.fetchedResultsController.managedObjectContext
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
var taskString:NSString
taskString = object.valueForKey("name") as String
cell.textLabel!.text = object.valueForKey("name") as? String
//Set accessory type
var request:NSFetchRequest = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %@", taskString)
var results : [NSManagedObject] = context.executeFetchRequest(request, error: nil) as [NSManagedObject]
if (results.count > 0) {
//Element exists
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
println("Cell is marked")
}
else {
//Doesn't exist
cell.accessoryType = UITableViewCellAccessoryType.None
println("Cell isn't marked")
}
答案 0 :(得分:0)
我敢打赌,问题来自于markedCell
在核心数据模型中被声明为可选属性,而name
或/和datum
不是可选的。
如果是这种情况,当你输入else
循环时,你的保存工作正常,因为那时你有:
markedCell == nil //this is allowed in your Core Data model
name != nil
datum != nil
但是,当您没有进入else
循环时,您有:
markedCell != nil
name == nil
datum == nil
,最后两行中的一行与您的Core Data模型不兼容。如果要使用原始代码,则需要确保此处提到的所有属性都声明为可选。