2015-02-06 107 views
5

我很困惑,一直無法追查任何教程或文件如何最好地做到這一點。核心數據與SWIFT:如何從關係實體中刪除對象?

問題:我有兩個實體,人員和位置。人可以有很多地點。我已經正確設置了一切,可以添加/刪除桌面視圖中的人員,沒有任何問題。

我遇到的問題是在創建第一個位置後嘗試添加和移除位置 - 第一次插入該位置時,它還會添加一個位置。

爲了這個目的,PersonModel(Person實體)類有:

class PersonModel: NSManagedObject { 

    @NSManaged var Name: String 
    @NSManaged var Age: String 
    @NSManaged var Location: NSOrderedSet 

} 

的LocationModel類(地點實體)有:

class LocationModel: NSManagedObject { 

    @NSManaged var State: String 
    @NSManaged var Person: PersonModel 

} 

什麼是訪問和刪除項目的最佳途徑在位置實體?我應該從PersonsModel還是通過LocationsModel刪除對象?

執行以下操作:

func deleteObject(rowIndex:NSIndexPath){ 
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 
    let managedContext = appDelegate.managedObjectContext! 
    let fetchRequest = NSFetchRequest(entityName:"Locations") 

    var error: NSError? 
    locationsArray = managedContext.executeFetchRequest(fetchRequest,error: &error)! 
    managedContext.deleteObject(locationsArray[rowIndex.row] as NSManagedObject) 

    var error:NSError? = nil 
    if (!managedContext.save(&error)){ 
     abort() 
    } 
} 

這並不工作,因爲它返回的所有位置,不只是與父/相關人員相關聯的對象的位置。必須有一個簡單的方法來做到這一點 - 也許有了謂詞?

有人可以幫助指向正確的方向嗎?

謝謝!

更新: 對於未來的人有相同的挑戰。

1)確保關係刪除規則是正確的。就我而言,我希望能夠刪除位置,但保留該人員。刪除規則需要被設置如下:位置 - 刪除規則:級聯,人 - 刪除規則:廢止

2)最後的代碼如下所示:

func deleteTrigger(rowIndex:NSIndexPath){ 

    var personRef: PersonModel = existingItem as PersonModel 
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 
    let managedContext:NSManagedObjectContext = appDelegate.managedObjectContext! 
    let fetchRequest = NSFetchRequest(entityName:"Locations") 
    let predicate = NSPredicate(format: "Person == %@", personRef) 
    fetchRequest.predicate = predicate 

    var error: NSError? = nil 
    locationArray = managedContext.executeFetchRequest(fetchRequest,error: &error)! 

    managedContext.deleteObject(locationArray[rowIndex.row] as NSManagedObject) 
    locationArray.removeAtIndex(rowIndex.row) 
    tableview.deleteRowsAtIndexPaths([rowIndex], withRowAnimation: UITableViewRowAnimation.Fade) 

    if (!managedContext.save(&error)){ 
    abort() 
    } 

} 

回答

3

使用謂詞是完全正確的。你想要設置爲fetchRequest

let predicate = NSPredicate(format: "uniqueKey == %@", "value") 
fetchRequest.predicate = predicate 

謂語,然後你就可以刪除結果

0

如何:

locationsArray = personRef.Location 

我認爲這是簡單得多

相關問題