CoreData添加对象

时间:2015-04-30 15:43:10

标签: ios swift core-data ios8

我制作了一个使用核心数据的应用。我做了一个函数,它将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")
    }

1 个答案:

答案 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模型不兼容。如果要使用原始代码,则需要确保此处提到的所有属性都声明为可选。