Skip to content

Commit

Permalink
Add Codable property support via a new attributeCodableTypeName user …
Browse files Browse the repository at this point in the history
…info key, as described in #375.
  • Loading branch information
atomicbird committed Sep 1, 2018
1 parent d4927d1 commit 28c0a72
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
11 changes: 11 additions & 0 deletions mogenerator.m
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,13 @@ - (NSString*)objectAttributeClassName {
if (!result) {
result = gSwift ? @"AnyObject" : @"NSObject";
}
} else if (gSwift && [self attributeType] == NSBinaryDataAttributeType) {
NSString *codableName = [self userInfo][@"attributeCodableTypeName"];
if (!codableName) {
result = @"Data";
} else {
result = codableName;
}
} else {
// Forcibly generate the correct class name in case we are
// running on macOS < 10.13
Expand Down Expand Up @@ -638,6 +645,10 @@ - (BOOL)usesCustomObjectAttributeType {
return (attributeValueClassName != nil);
}

- (BOOL)usesCustomCodableAttributeType {
return [self userInfo][@"attributeCodableTypeName"] != NULL;
}

- (NSString*)objectAttributeType {
NSString *result = [self objectAttributeClassName];
if ([result isEqualToString:@"Class"]) {
Expand Down
23 changes: 23 additions & 0 deletions templates/machine.swift.motemplate
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,29 @@ public extension <$managedObjectClassName$> {
setPrimitiveValue(value.rawValue, forKey: key)
}
}
<$elseif Attribute.usesCustomCodableAttributeType$>
// Attribute <$Attribute.name$> with Codable type <$Attribute.objectAttributeType$>
public<$if Attribute.isReadonly$> private(set)<$endif$> var <$Attribute.name$>: <$Attribute.objectAttributeType$>? {
get {
let key = <$managedObjectClassName$>.Attributes.<$Attribute.name$>
willAccessValue(forKey: key)
defer { didAccessValue(forKey: key) }

guard let primitiveValue = primitiveValue(forKey: key) as? Data else {
return nil
}

return try? JSONDecoder().decode(<$Attribute.objectAttributeType$>.self, from: primitiveValue)
}
set {
let key = <$managedObjectClassName$>.Attributes.<$Attribute.name$>
willChangeValue(forKey: key)
defer { didChangeValue(forKey: key) }

let primitiveValue = try? JSONEncoder().encode(newValue)
setPrimitiveValue(primitiveValue, forKey: key)
}
}
<$else$> <$comment usesRawValueEnumType = false $>
@NSManaged public<$if Attribute.isReadonly$> private(set)<$endif$> var <$Attribute.name$>: <$Attribute.objectAttributeType$><$if Attribute.isOptional$>?<$endif$>
<$endif$> <$comment usesRawValueEnumType $>
Expand Down

0 comments on commit 28c0a72

Please sign in to comment.