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

问题描述 投票:0回答:1

我想只更新相应属性中的最后一条记录。我的函数下面更新所有记录而不是最后一个。我尝试了其他替代方案,但仍然无法仅更新最后一条记录。任何建议都非常感谢!

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)")
    }      
  }
 }
}
swift core-data nsmanagedobject
1个回答
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)")
            }
        }
    }
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.