【发布时间】:2017-06-28 12:49:25
【问题描述】:
我想在 Swift 运行时检查属性数据类型的类型。就像插入时一样,我想检查实体中的特定属性是否接受日期类型或字符串类型的值。如何在 Swift 中实现这一点。
【问题讨论】:
-
你有例子吗?
-
实际上你应该在运行时知道属性及其类型,因为模型是只读的。
我想在 Swift 运行时检查属性数据类型的类型。就像插入时一样,我想检查实体中的特定属性是否接受日期类型或字符串类型的值。如何在 Swift 中实现这一点。
【问题讨论】:
您始终可以使用 NSAttributeDescription 类型的实体属性描述来找出模型中定义的属性的正确类型。
如果说你有一个 NSManagedObject 的子类,Person。然后,您可以使用以下代码中的示例在插入之前检查类型,
@objc(Person)
class Person: NSManagedObject {
@NSManaged
var name: String
@NSManaged
var age: NSNumber
@NSManaged
var dateOfBirth: Date
}
let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context) as! Person
if let attribute = person.entity.attributesByName["name"],
attribute.attributeType == .stringAttributeType {
// use your code here for custom logic
print("name is string")
}
if let attribute = person.entity.attributesByName["age"],
attribute.attributeType == .dateAttributeType {
// use your code here for custom logic
print("age is date")
}
【讨论】:
它是type(of:).E.g.,
let test: Int = 0
if type(of: test) == Int.self {
print("found")
}
【讨论】:
一般来说,在编写代码之前,您应该知道自己的模型是什么。 所以对只读模型进行反省似乎有点愚蠢。我想不出你为什么要这样做,但我相信你有充分的理由不分享。
您可以查看 managedObject entity 类方法(在您的子类上),它是 NSEntityDescription。或者,您可以直接从模型对象 (context.persistentStoreCoordinator.managedObjectModel.entites) 中获取所有实体描述,或者如果您知道实体的名称,则可以使用 context.persistentStoreCoordinator. managedObjectModel.entitiesByName["EntityName"]。实体描述将告诉您有关实体属性的所有信息。您可以查看每个属性并获得一个NSAttributeDescription,它将告诉您该属性的类型。
【讨论】: