在我的 ios swift 应用程序中,我有一个使用 Core Data 的数据库。
它有很多实体,所有实体都有一个整数字段,称为syncStatus
。有可能0, 1, or 2
.
启动时,我想循环遍历所有具有syncStatus = 1
并将其更改为0
有没有一种方法可以做到这一点,而无需单独获取每种类型并进行更改?
所以我想要的是:
- fetch
ALL
实体与syncStatus = 1
-
Loop
通过他们并设置syncStatus = 0
目前我正在一一做:
- fetch
UserEntities
with syncStatus = 1
- 循环遍历它们并设置
syncStatus = 0
- fetch
countryEntities
with syncStatus = 1
- 循环遍历它们并设置
syncStatus = 0
- 对每个实体一一执行相同的操作
code:
let allUsers = context?.fetch(FetchRequest<UserEntity>().filtered(with: "syncStatus", equalTo: "1"))
let allCountries = context?.fetch(FetchRequest<CountryEntity>().filtered(with: "syncStatus", equalTo: "1"))
.
.
.
我只是想找到一种通用方法,以防万一稍后我们添加另一个实体/表,我们不必返回此代码并将其添加到此处。
首先,获取所有条目并过滤它们比应用谓词要昂贵得多。
我建议使用带有静态方法的协议扩展。好处是您可以直接在类型上调用方法
protocol SyncStatusResettable
{
associatedtype Entity: NSManagedObject = Self
var syncStatus : String {get set}
static var entityName : String { get }
static func resetSyncStatus(in context: NSManagedObjectContext) throws
}
extension SyncStatusResettable where Entity == Self
{
static var entityName : String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
static func resetSyncStatus(in context: NSManagedObjectContext) throws
{
let request = NSFetchRequest<Entity>(entityName: entityName)
request.predicate = NSPredicate(format: "syncStatus == 1")
let items = try context.fetch(request)
for var item in items { item.syncStatus = "0" }
if context.hasChanges { try context.save() }
}
}
要使用它,请采用SyncStatusResettable
对全部NSManagedObject
子类和调用
do {
try UserEntity.resetSyncStatus(in: managedObjectContext)
try CountryEntity.resetSyncStatus(in: managedObjectContext)
} catch { print(error) }
managedObjectContext
是当前的NSManagedObjectContext
实例
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)