Fetch data from an Entity using Core Data in Swift

Posted By : Akshay Luthra | 30-Sep-2015

This blog is in continuation of my blog how to create an Entity using Core Data in Swift. Before reading this blog, I prefer you to have a look to it.

You can also read my blog on Insert and Delete from an Entity using Core Data in Swift.

 

In the “UserInfo.swift” file that I created in my previous blog, make a protocol for fetching the data from an Entity.

 (If your background is Java, then you can relate a Protocol in Swift with an Interface in Java)

 

Now you have to give the body of the protocol you have made so that you can use it.

For this create “UserInfoServices.swift” file

 

Then, import the CoreData and make a class “UserInfoServices” that extends the UserInfoProtocol and write the fetching of data logic in the class by making function.

 

import Foundation
import CoreData
import UIKit

class UserInfoServices:UserInfoProtocol{
    
    //Fetch values from User Info table
    func fetchUserInfoData() -> [AnyObject] {
        var dataToReturn = [AnyObject]()
        var data = Dictionary < String , AnyObject >()
        
        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext!
        let fetchRequest = NSFetchRequest(entityName:"UserInfo")
        var error: NSError?
        
        let fetchedResults =
        managedContext.executeFetchRequest(fetchRequest,
            error: &error) as? [NSManagedObject]
        
        if let results = fetchedResults {
            println("Data COUNT : \(results.count)")
            for var index = 0; index < results.count; index++ {
                let match = results[index] as NSManagedObject
                data = ["userid" : match.valueForKey("userid") as! String,
                    "name" : match.valueForKey("name") as! String,
                ]
                dataToReturn.append(data)
            }
        } else {
            println("Could not fetch \(error), \(error!.userInfo)")
        }
        
        return dataToReturn
    }
    
    
}


 

 

Thanks

 

About Author

Author Image
Akshay Luthra

Akshay Luthra has excellent experience in developing Cross Platform Mobile Apps using JavaScript and Titanium Framework. He loves listening to music and travelling new places.

Request for Proposal

Name is required

Comment is required

Sending message..