gpt4 book ai didi

swift - 通用 FetchRequest

转载 作者:可可西里 更新时间:2023-11-01 01:56:44 24 4
gpt4 key购买 nike

我有一个扩展 NSManagedObject 的静态函数得到这样的对象......

NSManagedObject.get(type: MYUser.self, with: ("id", "SomeUserId"), in: context)

extension NSManagedObject {

static func get<M: NSManagedObject>(type: M.Type, with kvp: (String, CVarArg), in context: NSManagedObjectContext) -> M? {

guard let name = entity().name else { return nil }
guard M.entity().propertiesByName[kvp.0] != nil else { Assert("\(name) does not have \(kvp.0)"); return nil }

let fetchRequest = NSFetchRequest<M>(entityName: name)
fetchRequest.predicate = NSPredicate(format: "\(kvp.0) == %@", kvp.1)

do {
let object = try context.fetch(fetchRequest)
if let foundObject = object.first { return foundObject }
return nil
} catch {
return nil
}
}
}

我想要的语法是

MYUser.get(with: ("id", "SomeUserId"), in: context)

并从发出调用的类中推断出类型...但我不确定用什么来代替这里的泛型

NSFetchRequest<M>(entityName: name)

NSFetchRequest<???>(entityName: name)

提前致谢

最佳答案

如果你不介意写两次MYUser,你可以去掉type参数并指定类型,这样Swift就可以推断出M :

extension NSManagedObject {

static func get<M: NSManagedObject>(with kvp: (String, CVarArg), in context: NSManagedObjectContext) -> M? {

guard let name = entity().name else { return nil }
guard M.entity().propertiesByName[kvp.0] != nil else {
print("\(name) does not have \(kvp.0)")
return nil
}

let fetchRequest = NSFetchRequest<M>(entityName: name)
fetchRequest.predicate = NSPredicate(format: "\(kvp.0) == %@", kvp.1)

do {
let object = try context.fetch(fetchRequest)
if let foundObject = object.first { return foundObject }
return nil
} catch {
return nil
}
}
}

// usage:
let user: MYUser? = MYUser.get(with: ("id", "SomeUserId"), in: context)

如果你不想写两次MYUser,那我想不出任何解决办法。如果 NSManagedObject 是一个协议(protocol),您可以在其中使用 Self

关于swift - 通用 FetchRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52530931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com