只需要更新NSManagedObject的最后一条记录

时间:2019-03-26 21:30:21

标签: swift core-data nsmanagedobject

我只想更新各自内的最后一条记录 属性。我下面的功能更新所有记录,而不仅仅是更新 持续。我尝试了其他替代方法,但仍然无法仅更新最后一条记录。任何建议将不胜感激!

public func updateLastRecordForEntityManagedObject(_ attributes:    
String...,booleanAttrType: [Bool],stringAttrType: [String,   
erManagedObject: [NSManagedObject] ,
inManagedObjectContext managedObjectContext: NSManagedObjectContext){

erManagedObject.forEach {

//Here, I attempt to Print the last record
if let lastRecord = erManagedObject.last{
    print(" Last Record: \(lastRecord)")

    // Use closures to pass the parameters ($0) and update the last 
    record 

    $0.setValue(booleanAttrType[0], forKeyPath: attributes[0])
    $0.setValue(stringAttrType[0], forKeyPath: attributes[1])

    //Attempt to save the respective records
    do {
    try managedObjectContext.save()
    } catch let error as NSError {
    print("(UPDATE_LAST_RECORD_ERROR) \(error), \
    (error.userInfo)")
    }      
  }
 }
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。解决方法如下:

public func updateLastRecordForEntityManagedObject(_ entity: String, _ 
attributes: String...,
booleanAttrType: [Bool], stringAttrType: [String],uuidAttrType:
[UUID],intAttrType:[Int64],
erManagedObject: [NSManagedObject] ,
inManagedObjectContext managedObjectContext: NSManagedObjectContext){

    // Retrieve and Print out the total records
    let recordCount =  erManagedObject.count
    print(" Total Records: \(recordCount)")

        //Obtain the index of the last record and update the record
        if let lastRecord = erManagedObject.last{
            //Print the last record
            print(" Last Record: \(lastRecord)")
            // Obtain the index
            let index = erManagedObject.endIndex - 1
            //Update the last record
            erManagedObject[index].setValue(booleanAttrType[0], forKeyPath: attributes[0])
            erManagedObject[index].setValue(stringAttrType[0], forKeyPath: attributes[1])

            //Attempt to save the record
            do {
                try managedObjectContext.save()
            } catch let error as NSError {
                print("(UPDATE_LAST_RECORD_ERROR) \(error), \(error.userInfo)")
            }
        }
    }
相关问题