我有一个像这样填充的数据库:
for defJson in listofDefinitions {
let newItemOfStock = Item()
print(defJson)
try! realm.write {
newItemOfStock.AverageCost = defJson["AverageCost"] as! Int
newItemOfStock.Barcode = defJson["Barcode"] as! String
newItemOfStock.Description = defJson["Description"] as! String
newItemOfStock.InternalUnique = defJson["InternalUnique"] as! Int
newItemOfStock.LastCost = defJson["LastCost"] as! Int
newItemOfStock.LimitToMainRegionUnique = defJson["LimitToMainRegionUnique"] as! Int
newItemOfStock.Notes = defJson["Notes"] as! String
newItemOfStock.StockCategoryUnique = defJson["StockCategoryUnique"] as! Int
newItemOfStock.StockCode = defJson["StockCode"] as! String
newItemOfStock.StockGroupUnique = defJson["StockGroupUnique"] as! Int
newItemOfStock.UnitDescriptor = defJson["UnitDescriptor"] as! String
self.newList.listOfItems.append(newItemOfStock)
}
}
但在我填充数据之前,我想删除仍在域数据库中的旧数据,我称之为func:
func cleanOldData() {
let itemListToBeRemoved = realm.objects(ListOfDefinitions)
let itemToBeRemoved = realm.objects(Item)
try! realm.write {
realm.delete(itemListToBeRemoved)
realm.delete(itemToBeRemoved)
}
}
但如果我不止一次调用此方法,则抛出此错误:
'RLMException', reason: 'Adding a deleted or invalidated object to a Realm is not permitted'
如何阻止这种情况发生,并且在填充之前仍然有一个干净的数据库
答案 0 :(得分:1)
如果您确实要删除Realm中的所有数据(而不仅仅是特定类型的数据),可以尝试使用deleteAll()
API:
try! realm.write {
realm.deleteAll()
}
答案 1 :(得分:0)
我认为问题在于:
self.newList.listOfItems.append(newItemOfStock)
我怀疑您可能从数据库中获取对象newList,然后删除所有对象,然后尝试将newItemOfStock对象添加到已删除对象的引用中。