1

I'm having trouble fetching my object from core data. Object looks like this:

class cilj: NSObject {
var imeCilja: String
var slikaCilja: String }

My entity is called Entity and has two Attributes "tekst" and "slika", both of type String. My save func is this:

func saveImage(goalName:String, imageName:String) {

  let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    let entityDescription =  NSEntityDescription.entityForName("Entity", inManagedObjectContext:managedContext)

    let thingToSaveToCD = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: managedContext)

    thingToSaveToCD.setValue(globalGoalTitle, forKey: "tekst")
    thingToSaveToCD.setValue(globalGoalImagePath, forKey: "slika")

    do {
        try managedContext.save()
        print("managed to save to core data")
        //5
       // listaObjekata.append(cilj5) as! [cilj]
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }

}

I use an alertController to pick up the text, and imagePicker to pick up image that I then store in documents and get the path. I store both of these in a global variables visible in the code above.

My fetch function is :

func coreDataFetch(){

    //core data fetch

    //1
    let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    //2
    let fetchRequest = NSFetchRequest(entityName: "Entity")


    do {
        let fetchedResults =  try managedContext.executeFetchRequest(fetchRequest) as! [cilj]
        listaObjekata = fetchedResults


    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

}

I have been through ray wenderlich's article on Core Data, Apple's documentation, a couple of YT videos but I still seem to be missing something. I would greatly appreciate any help. Thanks !

EDIT - here is my cellForRowAtIndexPath

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as! cellController
    let ciljZaPrikaz = listaObjekata[indexPath.item]

    cell.labelText.text = ciljZaPrikaz.imeCilja ?? "no text found"

    let path = getDocumentsDirectory().stringByAppendingPathComponent(ciljZaPrikaz.slikaCilja)
    cell.imageToShow.image = UIImage(contentsOfFile: path)

    return cell
}
7
  • Did you try this? let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [Entity] Commented Aug 16, 2016 at 19:47
  • Hey, yes I have and then it says on the line below it "Cannot assign a value of type [Entity] to type [cilj]. Commented Aug 16, 2016 at 19:55
  • You are saving with Entity and fetching with Entity then why the array is [cilj]?. Just try to print the fetchedResults and check what you are getting. Remove as! [Entity] or as! [cilj] and try. Commented Aug 16, 2016 at 19:59
  • I've tried it and when I enter a text and and an image I get [<Entity: 0x7fdffad0fe60> (entity: Entity; id: 0xd000000000040000 <x-coredata://ACEC5EBD-13BF-486E-BED3-65562FEFCD73/Entity/p1> ; data: <fault>)] Commented Aug 16, 2016 at 20:04
  • 1
    Yes, thats the data you are getting back from CoreData. you should cast it to your entity class. let enityModel = fetchedResults[0] as? Entity. Then you can access the value like entityModel. tekst Commented Aug 17, 2016 at 17:42

2 Answers 2

2

You are doing correct but just missing type casting to your model. Try below:

    let fetchedResults =  try managedContext.executeFetchRequest(fetchRequest)
    if let results = fetchResults where results.count > 0 {
        let entityModel = results[0] as? Entity
        let tekst = entityModel.tekst
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I would also like to add how I iterate through my return objects from core data:

 do {
        let fetchedResults =  try managedContext.executeFetchRequest(fetchRequest)
         listaObjekata.removeAll()
        for i in 0...(fetchedResults.count-1) {
             let enityModel = fetchedResults[i] as? Entity

                let thisToArray = cilj(imeCilja: (enityModel?.tekst!)!, slikaCilja: (enityModel?.slika!)!)
                listaObjekata.append(thisToArray)

        }

    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.