Skip to content

Commit e1d08df

Browse files
authored
Merge pull request #33 from admkopec/bugs/fix-optional-codable
Optional Codable property fix
2 parents 22cdf35 + 8f65cbb commit e1d08df

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

Sources/ManagedModels/SchemaCompatibility/NSAttributeDescription+Data.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ extension CoreData.NSAttributeDescription: SchemaProperty {
3232
if let baseType = attributeType.swiftBaseType(isOptional: isOptional) {
3333
return baseType
3434
}
35-
guard let attributeValueClassName else { return Any.self }
36-
return NSClassFromString(attributeValueClassName) ?? Any.self
35+
guard let attributeValueClassName else { return isOptional ? Any?.self : Any.self }
36+
return NSClassFromString(attributeValueClassName) ?? (isOptional ? Any?.self : Any.self)
3737
}
3838
set {
3939
// Note: This needs to match up w/ PersistentModel+KVC.

Tests/ManagedModelTests/CodablePropertiesTests.swift

+24
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,28 @@ final class CodablePropertiesTests: XCTestCase {
6969
XCTAssertNotNil(attribute.valueTransformerName)
7070
XCTAssertEqual(attribute.valueTransformerName, transformerName.rawValue)
7171
}
72+
73+
func testOptionalCodablePropertyEntity() throws {
74+
let entity = try XCTUnwrap(
75+
container?.managedObjectModel.entitiesByName["StoredAccess"]
76+
)
77+
78+
// Creating the entity should have registered the transformer for the
79+
// CodableBox.
80+
let transformerName = try XCTUnwrap(
81+
ValueTransformer.valueTransformerNames().first(where: {
82+
$0.rawValue.range(of: "CodableTransformerGSqVOO17ManagedModelTests8")
83+
!= nil
84+
})
85+
)
86+
let transformer = try XCTUnwrap(ValueTransformer(forName: transformerName))
87+
_ = transformer // to clear unused-wraning
88+
89+
let attribute = try XCTUnwrap(entity.attributesByName["optionalSip"])
90+
XCTAssertEqual(attribute.name, "optionalSip")
91+
XCTAssertTrue(attribute.valueType == Any?.self)
92+
// Fixtures.CodablePropertiesSchema.AccessSIP?.self)
93+
XCTAssertNotNil(attribute.valueTransformerName)
94+
XCTAssertEqual(attribute.valueTransformerName, transformerName.rawValue)
95+
}
7296
}

Tests/ManagedModelTests/Schemas/CodablePropertySchema.swift

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ extension Fixtures {
2020
var token : String
2121
var expires : Date
2222
var sip : AccessSIP
23+
var optionalSip : AccessSIP?
2324
}
2425

2526
struct AccessSIP: Codable {

0 commit comments

Comments
 (0)