I wrote two seperate functions fetchRecords and displayRecords written in Appdelegate Class. fetchRecords function will fetch all records from the entity and it is working fine.displayRecords function accepts the return value from fetchRecords function and prints all the records one by one.
I have one view controller which calls these two functions to do the desired task. My problem is result.count in displayRecords shows the total number of records available in fetched records.While printing the records one by one the value is nil.
override func viewDidLoad() {
super.viewDidLoad()
let fetchedRecords = AppDelegate().fetchRecords(fromEntity: "Dashboard")
AppDelegate().displayRecords(fromFetchedRecords: fetchedRecords)
}
And here is the fetchRecords and displayRecords functions written in AppDelegate Class
func fetchRecords(fromEntity entity:String) -> Array<AnyObject> {
var fetchedResult:Array<AnyObject> = []
let fetchRequest = NSFetchRequest()
let entityDescription = NSEntityDescription.entityForName(entity, inManagedObjectContext: self.managedObjectContext)!
fetchRequest.entity = entityDescription
do{
fetchedResult = try self.managedObjectContext.executeFetchRequest(fetchRequest)
}catch{
let fetchError = error as NSError?
print(fetchError!)
}
return fetchedResult
}
func displayRecords(fromFetchedRecords result:Array<AnyObject>) {
print("Total records:\(result.count)")
if (result.count > 0) {
for data in result {
let dashboard = data as! NSManagedObject
print("Value: \(dashboard.valueForKey("count"))")
}
}
}
I will share the data insertion code also.
func saveDashBoardData(dictionary: Dictionary<String, String>) {
print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask))
//Create Manage Object
let entityDescription: NSEntityDescription = NSEntityDescription.entityForName("Dashboard", inManagedObjectContext: self.managedObjectContext)!
for data in dictionary {
let dashboardObject = Dashboard(entity: entityDescription,insertIntoManagedObjectContext: self.managedObjectContext)
dashboardObject.type = data.0
dashboardObject.count = data.1
do {
try self.managedObjectContext.save()
print("Data saved succesfully")
}
catch {
print(error)
}
}
}
