所以我有一個一對多的核心數據結構核心數據一個一對多的插入與現有的關係迅速
extension Category {
@NSManaged var name: String?
@NSManaged var catHasExpenses: NSOrderedSet? }
extension Expenses {
@NSManaged var amount: NSNumber
@NSManaged var name: String?
@NSManaged var date: NSDate
@NSManaged var expenseHasCat: Category }
當應用程序啓動我插入的所有類別。當我想插入一個新的費用時,它也插入一個新的類別,我不想要。我的插入代碼:
func insertExpense(name: String?, amount: Double, date: NSDate, currentCat: Category) {
// Fetch current cateogory
let category: Category = self.fetchCurrentCategory(currentCat.name)!
NSLog("\(category.name)") //I know I have the correct category here
// Create new expense
let expense = NSEntityDescription.insertNewObjectForEntityForName("Expenses", inManagedObjectContext: self.managedObjectContext) as! Expenses
expense.expName = name
expense.amount = amount
expense.date = date
expense.expenseHasCat = category
do {
try self.managedObjectContext.save()
} catch {
NSLog("Error: \(error)")
}
}
func fetchCurrentCategory(selectedCat: String) -> Category? {
let fetchRequest = NSFetchRequest(entityName:"Category")
let predicate = NSPredicate(format: "name == %@", selectedCat)
fetchRequest.predicate = predicate
do{
if let fetchResults = try self.managedObjectContext.executeFetchRequest(fetchRequest) as? [Category] {
return fetchResults[0]
}
}
catch{
NSLog("Error: \(error)")
}
return nil
}
我知道我創建一個新的類別每次我插入一個新的費用,因爲我取,並在我的應用程序的開始計數的每個實體。
- 如何才能在現有類別中插入新費用?
請通過本教程:http://www.raywenderlich.com/14742/core-data-on-ios-5-tutorial-how-to-work-with-relations-and-predicates –
您的代碼有沒有創建任何新的類別對象,所以你遇到的問題是其他地方。你確定你在啓動時正確地執行了「插入所有類別」,而不是在那裏複製它們? – jrturton
不,我很確定只有當我插入新的費用時纔會創建新的類別。我只在entity.count = 0時創建類別。我添加了兩張關於我的xcdatamodeld的照片。 –