Mohamed Horani
Mohamed Horani

Reputation: 554

Saving objects into core data

There is something confuses me a lot... I'm following a tutorial but he didn't cover how most of the code is Done.

The tutorial using NSManagedObject Subclasses, the first time he checks for the sample data if it were in the Core Data we skip using return if the user launches the app for the first time the sample data goes into the Core Data. let's take a look.

 func inserSampleData()
  {
    let fetchRequest = NSFetchRequest(entityName: "Bowtie")
    fetchRequest.predicate = NSPredicate(format: "searchKey != nil")

    let count = managedContext.countForFetchRequest(fetchRequest, error: nil)

    if count > 0 { return } //break if we have the sample data already in the core data

    let path = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist")

    let dataArray = NSArray(contentsOfFile: path!)

    for dict in dataArray!
    { //1
        let entity = NSEntityDescription.entityForName("Bowtie", inManagedObjectContext: self.managedContext)
        let bowtie = Bowtie(entity: entity!, insertIntoManagedObjectContext: self.managedContext)
        let btDict = dict as! NSDictionary

       //// SOME CODE

        var error: NSError?

        if !managedContext.save(&error)
        {
            println("Some error \(error?.userInfo)")
        }

    }
  }

As in comment 1, he uses NSEntityDescription to get an an object of an entity, i believe we do so, to save our sample data into Core data, which can't be Done unless we call NSEntityDescription...

let's take a look at the 2nd func wear()

  func wear() {
    //currentBowtie is an instance of the NSManagedObject Subclass
    let times = currentBowtie.timesWorn.integerValue
    currentBowtie.timesWorn = NSNumber(integer: times + 1)
    currentBowtie.lastWorn = NSDate()

    var error: NSError?

    if managedContext.save(&error)
    {
        println("unable to save \(error) \(error?.userInfo)")
    }

  }

According the 2nd function he saved Directly to the disk, without specifying an Entity, also he didn't call NSEntityDescription.entityForName...

So how the application knew in which entity to save ?

Why he called NSEntityDescription in Func insertSampleData(), & he didn't use it in func wear() ?

Upvotes: 1

Views: 94

Answers (1)

rounak
rounak

Reputation: 9397

While the creation of a new Bowtie in Core Data, you need an entity description.

currentBowtie has already been created, so playing around with it further, and saving it doesn't require an entity description.

Upvotes: 1

Related Questions