0

I am trying to learn how to read data from a blog and save it to core data but the save is not working as intended. There are 4 blog entries and I expect to have 4 different entries in core data. Please see the code below and let me know where i went wrong:

 let task = session.dataTaskWithURL(url!, completionHandler:{(data , response, error) -> Void in
        if (error != nil){
            println(error)
        }else{
            var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary
            var managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
            let newBlog = NSEntityDescription.insertNewObjectForEntityForName("BlogDetails",inManagedObjectContext:managedObjectContext) as NSManagedObject
            var dateFormater = NSDateFormatter()
            dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss" //"yyyy-MM-dd"
            var readRequest = NSFetchRequest(entityName: "BlogDetails")
            for var i = 0; i < ((jsonResult["items"] as? NSArray)?.count)!; i++ {
                var item = jsonResult["items"]![i] as NSDictionary
                var blogAuthorDirectory = item["author"]! as NSDictionary
                var blogAuthor = blogAuthorDirectory["displayName"] as NSString
                var blogAuthorImageDirectory = blogAuthorDirectory["image"] as NSDictionary
                // concatenate String
                var blogAuthorImage =  blogAuthorImageDirectory["url"] as NSString
                var blogAuthorImageUrl = ("https:" + blogAuthorImage)
                var title = item["title"] as String
                // convert date from String
                var publishedDate:NSDate = dateFormater.dateFromString(stringTmp as NSString)!
                // read content
                var content = item["content"] as? NSString
                // Write it to core data
                newBlog.setValue(blogAuthorImageUrl, forKey: "image")
                newBlog.setValue(blogAuthor, forKey: "author")
                newBlog.setValue(title, forKey: "title")
                newBlog.setValue(publishedDate, forKey: "publisheddate")
                managedObjectContext.save(nil)
                var results = managedObjectContext.executeFetchRequest(readRequest, error: nil)
                println(results)
            }
        }
    })
    task.resume()

following are the entries in result in the last iteration: 1. It only has 3 dictionary counts out of which values in first 2 count has all items as nil. how is that being generated? 2. With every iteration, it overwrites value in last count and doesn't append it.

Thanks for your help.

ztan
  • 6,861
  • 2
  • 24
  • 44
ddesai
  • 499
  • 1
  • 6
  • 17

1 Answers1

3

If you want to append objects to your CoreData, you need to do insertIntoManagedObjectContext before you call the managedContext.save(nil) method.

However, your

let newBlog = NSEntityDescription.insertNewObjectForEntityForName("BlogDetails",inManagedObjectContext:managedObjectContext) as NSManagedObject

is declared outside of your for loop, so probably no new blog created after each iteration.

ztan
  • 6,861
  • 2
  • 24
  • 44
  • THANKS for your help!! It worked when I brought the line in the loop. so bottom line for every new dictionary block we have to re-instantiate NSEntityDescription.insertNewObjectForEntityForName. – ddesai Apr 09 '15 at 22:13