Skip to content

Commit

Permalink
Merge pull request #280 from dave256/swift-public
Browse files Browse the repository at this point in the history
public entities, optional import of base class module, and various Swift 1.2 fixes
  • Loading branch information
atomicbird committed Apr 29, 2015
2 parents 73fccca + d531234 commit c7417f6
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 74 deletions.
2 changes: 1 addition & 1 deletion templates/human.swift.motemplate
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@objc(<$managedObjectClassName$>)
class <$managedObjectClassName$>: _<$managedObjectClassName$> {
public class <$managedObjectClassName$>: _<$managedObjectClassName$> {

// Custom logic goes here.

Expand Down
66 changes: 34 additions & 32 deletions templates/machine.swift.motemplate
Original file line number Diff line number Diff line change
Expand Up @@ -3,50 +3,52 @@

import CoreData

<$if hasCustomBaseCaseImport$>import <$baseClassImport$><$endif$>

<$if noninheritedAttributes.@count > 0$>
enum <$managedObjectClassName$>Attributes: String {<$foreach Attribute noninheritedAttributes do$>
public enum <$managedObjectClassName$>Attributes: String {<$foreach Attribute noninheritedAttributes do$>
case <$Attribute.name$> = "<$Attribute.name$>"<$endforeach do$>
}
<$endif$>

<$if noninheritedRelationships.@count > 0$>
enum <$managedObjectClassName$>Relationships: String {<$foreach Relationship noninheritedRelationships do$>
public enum <$managedObjectClassName$>Relationships: String {<$foreach Relationship noninheritedRelationships do$>
case <$Relationship.name$> = "<$Relationship.name$>"<$endforeach do$>
}
<$endif$>

<$if noninheritedFetchedProperties.@count > 0$>
enum <$managedObjectClassName$>FetchedProperties: String {<$foreach FetchedProperty noninheritedFetchedProperties do$>
public enum <$managedObjectClassName$>FetchedProperties: String {<$foreach FetchedProperty noninheritedFetchedProperties do$>
case <$FetchedProperty.name$> = "<$FetchedProperty.name$>"<$endforeach do$>
}
<$endif$>

<$if hasUserInfoKeys$>
enum <$managedObjectClassName$>UserInfo: String {<$foreach UserInfo userInfoKeyValues do$>
public enum <$managedObjectClassName$>UserInfo: String {<$foreach UserInfo userInfoKeyValues do$>
case <$UserInfo.key$> = "<$UserInfo.key$>"<$endforeach do$>
}
<$endif$>

@objc
@objc public
class _<$managedObjectClassName$>: <$customSuperentity$> {

// MARK: - Class methods

<$if hasCustomSuperentity$>override <$endif$>class func entityName () -> String {
<$if hasCustomSuperentity$>override <$endif$>public class func entityName () -> String {
return "<$name$>"
}

<$if hasCustomSuperentity$>override <$endif$>class func entity(managedObjectContext: NSManagedObjectContext!) -> NSEntityDescription! {
<$if hasCustomSuperentity$>override <$endif$>public class func entity(managedObjectContext: NSManagedObjectContext!) -> NSEntityDescription! {
return NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: managedObjectContext);
}

// MARK: - Life cycle methods

override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
public override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}

convenience init(managedObjectContext: NSManagedObjectContext!) {
public convenience init(managedObjectContext: NSManagedObjectContext!) {
let entity = _<$managedObjectClassName$>.entity(managedObjectContext)
self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
}
Expand All @@ -56,18 +58,18 @@ class _<$managedObjectClassName$>: <$customSuperentity$> {
<$if Attribute.hasDefinedAttributeType$>
<$if Attribute.hasScalarAttributeType$>
<$if Attribute.isReadonly$>
@NSManaged
@NSManaged public
let <$Attribute.name$>: NSNumber?
<$else$>
@NSManaged
@NSManaged public
var <$Attribute.name$>: NSNumber?
<$endif$>
<$else$>
<$if Attribute.isReadonly$>
@NSManaged
@NSManaged public
let <$Attribute.name$>: <$Attribute.objectAttributeType$><$if Attribute.isOptional$>?<$endif$>
<$else$>
@NSManaged
@NSManaged public
var <$Attribute.name$>: <$Attribute.objectAttributeType$><$if Attribute.isOptional$>?<$endif$>
<$endif$>
<$endif$>
Expand All @@ -78,11 +80,11 @@ class _<$managedObjectClassName$>: <$customSuperentity$> {
// MARK: - Relationships
<$foreach Relationship noninheritedRelationships do$>
<$if Relationship.isToMany$>
@NSManaged
@NSManaged public
var <$Relationship.name$>: <$Relationship.immutableCollectionClassName$>

<$else$>
@NSManaged
@NSManaged public
var <$Relationship.name$>: <$Relationship.destinationEntity.managedObjectClassName$><$if Relationship.isOptional$>?<$endif$>

// func validate<$Relationship.name.initialCapitalString$>(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {}
Expand Down Expand Up @@ -132,17 +134,17 @@ class _<$managedObjectClassName$>: <$customSuperentity$> {
return self.fetch<$FetchRequest.name.initialCapitalString$>(managedObjectContext<$foreach Binding FetchRequest.bindings do2$>, <$Binding.name$>: <$Binding.name$><$endforeach do2$>, error: nil)
}

class func fetch<$FetchRequest.name.initialCapitalString$>(managedObjectContext: NSManagedObjectContext!<$foreach Binding FetchRequest.bindings do2$>, <$Binding.name$>: <$Binding.type$><$endforeach do2$>, error outError: NSErrorPointer) -> [AnyObject] {
let model = managedObjectContext.persistentStoreCoordinator.managedObjectModel
let substitutionVariables = [<$if FetchRequest.hasBindings$><$foreach Binding FetchRequest.bindings do2$>
class func fetch<$FetchRequest.name.initialCapitalString$>(managedObjectContext: NSManagedObjectContext!<$foreach Binding FetchRequest.bindings do2$>, <$Binding.name$>: <$Binding.type$><$endforeach do2$>, error outError: NSErrorPointer) -> [AnyObject]! {
let model = managedObjectContext.persistentStoreCoordinator!.managedObjectModel
let substitutionVariables : [NSObject : AnyObject] = [<$if FetchRequest.hasBindings$><$foreach Binding FetchRequest.bindings do2$>
"<$Binding.name$>": <$Binding.name$>,
<$endforeach do2$><$else$>:<$endif$>]

let fetchRequest = model.fetchRequestFromTemplateWithName("<$FetchRequest.name$>", substitutionVariables: substitutionVariables)
assert(fetchRequest != nil, "Can't find fetch request named \"<$FetchRequest.name$>\".")

var error: NSError? = nil
let results = managedObjectContext.executeFetchRequest(fetchRequest, error: &error)
let results = managedObjectContext.executeFetchRequest(fetchRequest!, error: &error)

if error != nil {
outError.memory = error
Expand All @@ -154,7 +156,7 @@ class _<$managedObjectClassName$>: <$customSuperentity$> {
<$endforeach do$>

<$foreach FetchedProperty noninheritedFetchedProperties do$>
@NSManaged
@NSManaged public
let <$FetchedProperty.name$>: [<$FetchedProperty.entity.managedObjectClassName$>]
<$endforeach do$>
}
Expand All @@ -163,28 +165,28 @@ class _<$managedObjectClassName$>: <$customSuperentity$> {
extension _<$managedObjectClassName$> {

func add<$Relationship.name.initialCapitalString$>(objects: <$Relationship.immutableCollectionClassName$>) {
let mutable = self.<$Relationship.name$>.mutableCopy() as NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
mutable.union<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set(objects)
self.<$Relationship.name$> = mutable.copy() as NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
let mutable = self.<$Relationship.name$>.mutableCopy() as! NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
mutable.union<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set(objects as! Set<NSObject>)
self.<$Relationship.name$> = mutable.copy() as! NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
}

func remove<$Relationship.name.initialCapitalString$>(objects: <$Relationship.immutableCollectionClassName$>) {
let mutable = self.<$Relationship.name$>.mutableCopy() as NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
mutable.minus<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set(objects)
self.<$Relationship.name$> = mutable.copy() as NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
let mutable = self.<$Relationship.name$>.mutableCopy() as! NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
mutable.minus<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set(objects as! Set<NSObject>)
self.<$Relationship.name$> = mutable.copy() as! NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
}

func add<$Relationship.name.initialCapitalString$>Object(value: <$Relationship.destinationEntity.managedObjectClassName$>!) {
let mutable = self.<$Relationship.name$>.mutableCopy() as NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
let mutable = self.<$Relationship.name$>.mutableCopy() as! NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
mutable.addObject(value)
self.<$Relationship.name$> = mutable.copy() as NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
self.<$Relationship.name$> = mutable.copy() as! NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
}

func remove<$Relationship.name.initialCapitalString$>Object(value: <$Relationship.destinationEntity.managedObjectClassName$>!) {
let mutable = self.<$Relationship.name$>.mutableCopy() as NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
let mutable = self.<$Relationship.name$>.mutableCopy() as! NSMutable<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
mutable.removeObject(value)
self.<$Relationship.name$> = mutable.copy() as NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
self.<$Relationship.name$> = mutable.copy() as! NS<$if Relationship.jr_isOrdered$>Ordered<$endif$>Set
}

}
<$endif$><$endforeach do$>
<$endif$><$endforeach do$>
43 changes: 17 additions & 26 deletions test/MogenSwiftTest/MogenSwiftTest/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@ class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet var window: NSWindow?


func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
}

func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}

@IBAction func saveAction(sender: AnyObject) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
var error: NSError? = nil
Expand All @@ -30,7 +21,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
println("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
}
if !moc.save(&error) {
NSApplication.sharedApplication().presentError(error)
NSApplication.sharedApplication().presentError(error!)
}
}
}
Expand All @@ -50,7 +41,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

let modelURL = NSBundle.mainBundle().URLForResource("MogenSwiftTest", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!)
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
Expand All @@ -70,31 +61,31 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let optProperties: NSDictionary? = applicationFilesDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)

if let properties = optProperties {
if !properties[NSURLIsDirectoryKey].boolValue {
if !properties[NSURLIsDirectoryKey]!.boolValue {
// Customize and localize this error.
let failureDescription = "Expected a folder to store application data, found a file \(applicationFilesDirectory.path)."
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = failureDescription
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 101, userInfo: dict)
var errorDict = [NSObject : AnyObject ]()
errorDict[NSLocalizedDescriptionKey] = failureDescription
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 101, userInfo: errorDict)

NSApplication.sharedApplication().presentError(error)
NSApplication.sharedApplication().presentError(error!)
return nil
}
} else {
var ok = false
if error!.code == NSFileReadNoSuchFileError {
ok = fileManager.createDirectoryAtPath(applicationFilesDirectory.path, withIntermediateDirectories: true, attributes: nil, error: &error)
ok = fileManager.createDirectoryAtPath(applicationFilesDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error)
}
if !ok {
NSApplication.sharedApplication().presentError(error)
NSApplication.sharedApplication().presentError(error!)
return nil
}
}

let url = applicationFilesDirectory.URLByAppendingPathComponent("MogenSwiftTest.storedata")
var coordinator = NSPersistentStoreCoordinator(managedObjectModel: mom)
if coordinator.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
NSApplication.sharedApplication().presentError(error)
NSApplication.sharedApplication().presentError(error!)
return nil
}
_persistentStoreCoordinator = coordinator
Expand All @@ -110,11 +101,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

let coordinator = self.persistentStoreCoordinator
if !coordinator {
var dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the store"
dict[NSLocalizedFailureReasonErrorKey] = "There was an error building up the data file."
let error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
if !(coordinator != nil) {
var errorDict = [NSObject : AnyObject ]()
errorDict[NSLocalizedDescriptionKey] = "Failed to initialize the store"
errorDict[NSLocalizedFailureReasonErrorKey] = "There was an error building up the data file."
let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: errorDict)
NSApplication.sharedApplication().presentError(error)
return nil
}
Expand All @@ -137,7 +128,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.

if !_managedObjectContext {
if !(_managedObjectContext != nil) {
// Accesses the underlying stored property because we don't want to cause the lazy initialization
return .TerminateNow
}
Expand All @@ -154,7 +145,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
var error: NSError? = nil
if !moc.save(&error) {
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(error)
let result = sender.presentError(error!)
if (result) {
return .TerminateCancel
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class _MyEntityMO: NSManagedObject {

/// pragma mark - Life cycle methods

init(entity: NSEntityDescription!, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class _UnorderedToManyDstMO: NSManagedObject {

/// pragma mark - Life cycle methods

init(entity: NSEntityDescription!, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class _UnorderedToManySrcMO: NSManagedObject {

/// pragma mark - Life cycle methods

init(entity: NSEntityDescription!, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}

Expand Down Expand Up @@ -61,32 +61,32 @@ class _UnorderedToManySrcMO: NSManagedObject {
}

class func fetchAllUnorderedToManySrcs(managedObjectContext: NSManagedObjectContext!, error outError: NSErrorPointer) -> [AnyObject] {
let model = managedObjectContext.persistentStoreCoordinator.managedObjectModel
let model = managedObjectContext.persistentStoreCoordinator!.managedObjectModel
let substitutionVariables = [:]

let fetchRequest = model.fetchRequestFromTemplateWithName("allUnorderedToManySrcs", substitutionVariables: substitutionVariables)
let fetchRequest = model.fetchRequestFromTemplateWithName("allUnorderedToManySrcs", substitutionVariables: substitutionVariables as [NSObject : AnyObject])
assert(fetchRequest != nil, "Can't find fetch request named \"allUnorderedToManySrcs\".")

var error: NSError? = nil
let results = managedObjectContext.executeFetchRequest(fetchRequest, error: &error)
let results = managedObjectContext.executeFetchRequest(fetchRequest!, error: &error)

if error {
if (error != nil) {
outError.memory = error
}

return results
return results!
}

}

extension _UnorderedToManySrcMO {

func addRelationship(objects: NSSet) {
self.relationshipSet().unionSet(objects)
self.relationshipSet().unionSet(objects as Set<NSObject>)
}

func removeRelationship(objects: NSSet) {
self.relationshipSet().minusSet(objects)
self.relationshipSet().minusSet(objects as Set<NSObject>)
}

func addRelationshipObject(value: UnorderedToManyDstMO!) {
Expand Down
2 changes: 1 addition & 1 deletion test/MogenSwiftTest/MogenSwiftTest/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@

import Cocoa

NSApplicationMain(C_ARGC, C_ARGV)
NSApplicationMain(Process.argc, Process.unsafeArgv)
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import MogenSwiftTest

class MogenSwiftTestTests: XCTestCase {
func newMoc() -> (NSManagedObjectContext) {
let momURL : NSURL = NSBundle.mainBundle().URLForResource("MogenSwiftTest", withExtension: "momd")
let mom : NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: momURL)
let momURL : NSURL = NSBundle.mainBundle().URLForResource("MogenSwiftTest", withExtension: "momd")!
let mom : NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: momURL)!
let psc : NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: mom);
let ps : NSPersistentStore = psc.addPersistentStoreWithType(
NSInMemoryStoreType,
configuration: nil,
URL: nil,
options: nil,
error: nil)
error: nil)!
let moc : NSManagedObjectContext = NSManagedObjectContext()
moc.persistentStoreCoordinator = psc
return moc
Expand Down Expand Up @@ -87,7 +87,7 @@ class MogenSwiftTestTests: XCTestCase {

extension NSEntityDescription {
class func entityForName_workaround(entityName: String!, inManagedObjectContext context: NSManagedObjectContext!) -> NSEntityDescription! {
let entities = context.persistentStoreCoordinator.managedObjectModel.entitiesByName;
let entities = context.persistentStoreCoordinator!.managedObjectModel.entitiesByName;
let keys = Array(entities.keys)
var result : NSEntityDescription?
for (key, value) in entities {
Expand Down

0 comments on commit c7417f6

Please sign in to comment.