title: Swift NSManagedObject factory
body: <p>I'm newish to Swift 2.0 and new to Core Data. </p>
  
  <p><strong>I'm looking to "un-flatten" an assortment of Core Data <code>NSManagedObject</code>s. Right now, I'm using predicates and joining on a property, "parentNameID" and "nameID". I do have itemCategory and itemCategoryChildren relationships set up in the Core Data GUI, and I'd like to move toward joining on this relationship rather than a "flat" join via parentNameID&lt;->>nameID and predicates. I suspect I'm really close but my <code>fetchedResultsParentID</code> container is always empty.</strong></p>
  
  <p>Please don't direct me to SuperAwesomeAPI or StudlyGreatAPI; I'm looking to do this via native Core Data calls. I saw what could have been a discussion of great value get killed by an off-hand mention of an external API used.</p>
  
  <p>I'm trying to <strong>convert a class of mine with a factory method--<code>enumerate()</code>--to Core Data</strong>. The <code>enumerate()</code> call works as expected--returns an array of class objects--when my class is of <code>NSObject</code>--but I can't seem to "un-flatten" the assortment of <code>NSManagedObject</code>s into a full Core Data relationship. </p>
  
  <p><strong>What I have:</strong> A class of Items (NSObject) and a factory class function, <code>enumerate()</code>, that returns an array of Items.</p>
  
  <p><strong>What I'd like:</strong> A class of Items (NSManagedObject) and a factory class function, enumerate(), that returns NSManagedObjects. </p>
  
  <p><strong>What I've done:</strong> Within <code>enumerate()</code> there are item properties being set, and an array of these items being generated. I'm calling <code>enumerate()</code> externally, from the <code>AppDelegate.Swift</code> file: <code>var items = Item.enumerate()</code> and then was setting properties on an NSManagedObject via <code>setValue()</code>.</p>
  
  <p>I've looked at all sorts of answers, and the only thing I could really find that talked about a factory and Core Data was <a href="https://stackoverflow.com/questions/24792372/swift-coredata-nsmanagedobject">this post</a>.</p>
  
  <p>I'm certainly not above fetching these items from a JSON or XML file, and will likely move that way in future, but this seems harder than a factory class making an array. If not, please let me know!!</p>
  
  <p>Related <code>AppDelegate.Swift</code> function:</p>
  
  <pre><code>func preloadData(EntityName: String) {
      // Remove any data that may exist
      removeData(EntityName)
  
      var items = AllItems.enumerate()
  
      print("Array enumerated with \(items.count) items.")
  
      for item in items {
          let newItem = NSEntityDescription.insertNewObjectForEntityForName(EntityName, inManagedObjectContext: managedObjectContext) as NSManagedObject
          // Required
          newItem.setValue(item.isCategory, forKey: "isCategory")
          newItem.setValue(item.name, forKey: "name")
          newItem.setValue(item.shortDetail, forKey: "shortDetail")
          newItem.setValue(item.itemID, forKey: "itemID")
  
          if (item.parentItemID != nil) {
              let fetchRequestParentID = NSFetchRequest(entityName:EntityName)
              let predicateParentID = NSPredicate(format: "parentItemID == %i", item.parentItemID!)
              fetchRequestParentID.predicate = predicateParentID
              do {
                  let fetchedResultsParentID = try managedObjectContext.executeFetchRequest(fetchRequestParentID) as? [NSManagedObject]
                  // success ...
                  // THIS IS WHERE THINGS FAIL.
                  //                    newItem.setValue(fetchedResultsParentID, forKey: "itemCategory")
                  newItem.setValue(fetchedResultsParentID, forKeyPath: "itemCategory")
              } catch let error as NSError {
                  // failure
                  print("Fetch failed: \(error.localizedDescription)")
              }
  
                  //                let fetchRequestParentID = NSFetchRequest(entityName: EntityName)
                  //                fetchRequestParentID.fetchLimit = 1
                  //                
                  //                let fetchedEntitiesParentID = self.managedObjectContext.executeFetchRequest(fetchRequestParentID)
                  //                
                  //                newItem.setValue(newItem, forKey: "itemCategory")
          }
      }
  
      items.removeAll()
  
      do {
          try managedObjectContext.save()
      } catch let error as NSError {
          print("Failed: \(error.localizedDescription)")
      }
  }
  </code></pre>