我想在 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")
}
关于ios - 如何在运行时检查核心数据属性类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44802961/