所以我有一对多的核心数据结构
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
}
我知道每次插入新费用时都会创建一个新类别,因为我在应用程序开始时获取并计算每个实体。
答案 0 :(得分:1)
为什么Expenses
(可能应该是Expense
)的父实体为Category
?这意味着您可能不想要的某些属性继承,如果您依赖Category
个实体的数量,那么所有Expenses
实体也将包含在计数。
除非你有充分的理由,否则你通常不想在Core Data中进行实体继承。所有实体和继承的实体都存储在数据库的同一个表中,这根本不能帮助提高性能。