Problem
I am new to IOS development, and have been struggling with Core Data. I am trying to create a settings page with a switch. I need to remember if this switch is turned on or off. I created a core data application, and have managed to figure out how to save the value of the switch to the attribute. The code below does this, I just can't figure out how to get the saved value of the switch back as on or off. How would I do this? Thanks!
Picture of Core Data
Code:
import UIKit
import CoreData
class preferencesStuff: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Settings")
request.returnsObjectsAsFaults = false;
var results:NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0){
if results[results.count-1] as NSObject == 1 {
println("ON")
}
}else{
println("NO RESULTS")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var fractSwitchValue: UISwitch!
#IBAction func fractSwitch(sender: AnyObject) {
if fractSwitchValue.on == true {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newSetting = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: context) as NSManagedObject
newSetting.setValue(true, forKey: "fractionOnOff")
context.save(nil)
//println(newSetting)
}
else {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newSetting = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: context) as NSManagedObject
newSetting.setValue(false, forKey: "fractionOnOff")
context.save(nil)
//println(newSetting)
}
}
}
I just did your example with CoreData. I just happened to store an NSString instead of a Bool. It's not optimized, but it should get you going.
import UIKit
import CoreData
class ViewController: UIViewController {
var state: NSString = ""
#IBOutlet weak var fractSwitchValue: UISwitch!
#IBAction func fractSwitch(sender: AnyObject) {
if fractSwitchValue.on == true {
state = "On"
save(state)
}
else {
state = "Off"
save(state)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var appDel = UIApplication.sharedApplication().delegate as AppDelegate
var context = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Settings")
var error: NSError?
var results = context.executeFetchRequest(request, error: &error) as [NSManagedObject]?
if let fetchedResults = results {
state = fetchedResults[fetchedResults.count - 1].valueForKey("fractionOnOff") as String!
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
if state == "On" {
fractSwitchValue.setOn(true, animated: true)
} else {
fractSwitchValue.setOn(false, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func save(string: NSString) {
let appDel = UIApplication.sharedApplication().delegate as AppDelegate
let context = appDel.managedObjectContext!
let entity = NSEntityDescription.entityForName("Settings", inManagedObjectContext: context)
let setting = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
setting.setValue(string, forKey: "fractionOnOff")
println(string)
var error: NSError?
if !context.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
}
}
I would use NSUserDefaults for this case. It's much easier to use than Core Data when storing user preferences. For example, you would store the property using
NSUserDefaults.standardUserDefaults().setBool(value, forKey: "fractionPreference")
and retrieve it using
let value = NSUserDefaults.standardUserDefaults().boolForKey("fractionPreference")
Related
Plese share some sample code snippet for database save details and fetch saved details in swift 4
This is my answer
Step 1 : Create Coredata Stack Class see below
var coreDataStack: CoreDataStack = CoreDataStack() // add this line on appDelegate
class Stack
{
lazy var managedObjectModel: NSManagedObjectModel = {
let modelUrl = Bundle.main.url(forResource: "Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelUrl)!
}()
lazy var peristentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let applicationDocumentsDirectory: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
let persistentStoreUrl: URL = applicationDocumentsDirectory.appendingPathComponent("Model.sqlite")
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreUrl, options: nil)
}
catch {
fatalError("Persistent store error! \(error)")
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let managedObjectContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.peristentStoreCoordinator
return managedObjectContext
}()
func saveContext() {
if self.managedObjectContext.hasChanges {
do {
try self.managedObjectContext.save()
}
catch {
fatalError("There was an error saving the managed object context \(error)")
}
}
}
}
Step 2 : Create entity
Step 3 : Create ManagedObjectModelSubclass -- Editor -> ManagedObjectModelSubclass
Step 4 : import core data on class and add below code
var person = [Person]() //[Person] here denote subclassclass name
var appDelegate = UIApplication.shared.delegate as! AppDelegate
let personEntity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: "EntityName", in: self.appDelegate.coreDataStack.managedObjectContext)
if personEntity != nil {
let person1: Person = Person(entity: personEntity!, insertInto: self.appDelegate.coreDataStack.managedObjectContext)
person1.name = "name"
person1.country = "US"
person1.age = "26"
person1.place = "NewYork"
}
Step 5 : For fetch data use below code
var persons: [Person] = [] // subclass name
var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
var listdata = [ModelClass]() // create a modelclass object
func fetchDemoData() {
let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
do {
if let results = try self.appDelegate.coreDataStack.managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] {
let personList: [Person]? = results as? [Person]
if personList != nil {
self.persons = personList!
for eachData in persons {
let name = eachData.name as String!
let username = eachData.age as String!
let email = eachData.country as String!
let address = eachData.place as! [String : Any]
self.listdata.append(ModelClass(name: name!, username: username!,email : email!,address : address))
}
//self.tableview.reloadData()
}
}
}
catch {
fatalError("There was an error fetching the items")
}
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
newUser.setValue("Shashikant", forKey: "username")
newUser.setValue("1234", forKey: "password")
newUser.setValue(1, forKey: "age")
do {
try context.save()
} catch {
print("Failed saving")
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//request.predicate = NSPredicate(format: "age = %#", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "id") as! String)
print(data.value(forKey: "username") as! String)
}
} catch {
print("Failed")
}
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet weak var txtName: UITextField!
#IBOutlet weak var txtId: UITextField!
#IBOutlet weak var txtMark: UITextField!
#IBOutlet weak var labelStatus: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buutonSave(_ sender: Any) {
let appDelegateObject:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObject:NSManagedObjectContext = appDelegateObject.persistentContainer.viewContext
let entityDescription =
NSEntityDescription.entity(forEntityName: "Student",
in: managedObject)
var student = NSManagedObject(entity: entityDescription!, insertInto: managedObject)
[student .setValue(self.txtName.text, forKey: "name")]
[student .setValue(self.txtId.text, forKey: "id")]
[student .setValue(self.txtMark.text, forKey: "mark")]
labelStatus.text = "Contact Saved"
}
#IBAction func buttonFind(_ sender: Any) {
let appDelegateObject:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObject:NSManagedObjectContext = appDelegateObject.persistentContainer.viewContext
let entityDescription =
NSEntityDescription.entity(forEntityName: "Student",
in: managedObject)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDescription
let pred = NSPredicate(format: "(name = %#)", txtName.text!)
request.predicate = pred
do {
var results =
try managedObject.fetch(request)
if results.count > 0 {
let match = results[0] as! NSManagedObject
txtName.text = match.value(forKey: "name") as? String
txtId.text = match.value(forKey: "id") as? String
txtMark.text = match.value(forKey: "mark") as? String
labelStatus.text = "Matches found: \(results.count)"
} else {
labelStatus.text = "No Match"
}
} catch let error as NSError {
labelStatus.text = error.localizedFailureReason
}
}
}
//CoreDataRose
ad = (UIApplication.shared.delegate as! AppDelegate) moc = ad.persistentContainer.viewContext
actorEntity = NSEntityDescription.entity(forEntityName: "Actors", in: moc)
func fetch() {
let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Actors")
do{
let actorsArr = try moc.fetch(fetchReq)
for i in 0..<actorsArr.count
{
let mo:NSObject = actorsArr[i] as! NSManagedObject
print(mo.value(forKey: "empFName")!)
DispatchQueue.main.async {
actorsArray.append(actors(firstName: (mo.value(forKey: "empFName") as? String), lastName: (mo.value(forKey: "empLName") as? String ), age: (mo.value(forKey: "empAge") as? Int)))
}
}
}catch{
print("Error Message")
}
}
#IBAction func submitBtn(_ sender: Any) {
// var secondView = storyboard?.instantiateViewController(withIdentifier: "DisplayView") as! DisplayView
// secondView.firstView = self
// present(secondView, animated: true)
actorsArray.append(actors(firstName: "\(firstNameTF.text!)", lastName: "\(lastNameTF.text!)", age: ageTF.text! as? Int))
var mo2 = NSManagedObject(entity: actorEntity, insertInto: moc)
mo2.setValue(firstNameTF.text, forKey: "empFName")
mo2.setValue(lastNameTF.text, forKey: "empLName")
mo2.setValue(Int(ageTF.text!), forKey: "empAge")
do{
try moc.save()
}catch{
print("Error")
}
}
#IBAction func chooseImageButton(_ sender: Any) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerController.SourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
{
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
{
importImage.image = image
}
else{
print("error message")
}
self.dismiss(animated: true, completion: nil)
}
Hello I am having an issue with core data in Swift, this doesn't show an error but also doesn't print anything when I believe it should be returning 'Joe' + 'pass' in console. Could anyone help please?
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
newUser.setValue("Joe", forKey: "username")
newUser.setValue("pass", forKey: "password")
do {
try context.save()
} catch let error {
print("Couldn't save user data")
print(error)
}
let request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
var results = try context.executeFetchRequest(request)
results = results as! [NSManagedObject]
if results.count > 0 {
for results in results {
print(results)
}}
} catch let error as NSError {
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You should create your own coredata class (as a subclass of NSManagedObject) and then create the array out of that class.
specify exactly what you want to print. In your case
newUser.username
I finally realised what my issue was, I hadn't actually renamed by Entity to 'Users' I'd kept it as 'Entity' so when I was doing
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
let request = NSFetchRequest(entityName: "Users")
I should have actually have replaced both Users with 'Entity' which now fixes my issue, thanks I guess for your help anyway!
I'm trying to store an NSDate in CoreData and then retrieve it and apply it to a variable
#IBOutlet weak var buttonTimer1: UIButton! {
setTimersDate.zero = NSDate()
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
var buttonTimer1Date = NSEntityDescription.insertNewObjectForEntityForName("TimerDates", inManagedObjectContext: context) as NSManagedObject
buttonTimer1Date.setValue(setTimersDate.zero, forKey: "dates")
do {
try context.save()
} catch {
print("Dates saving error")
}
}
#IBOutlet weak var setTimer1: UIButton! {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //Import Appdelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
var request = NSFetchRequest(entityName: "TimerDates")
request.returnsObjectsAsFaults = false
do {
print(request[0].buttonTimer1Date)
} catch {
print("Cannot request data")
}
}
This saves and prints the current date on the console, so I know the date is being stored. However, I want to set request[0] back to an NSDate().
Is this possible, or am I going about this the wrong way?
Cheers.
You need to execute the fetch request
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate //Import Appdelegate
let context = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "TimerDates")
do {
let allDates = try context.executeFetchRequest(request) as! [NSManagedObject]
if !allDates.isEmpty { print(allDates[0].valueForKey("dates") }
} catch let error as NSError {
print("Cannot request data", error)
}
However this code as a closure of an IBOutlet is a bit weird.
I want to create login and signup functions within Swift using Core Data.
This is my code to store the data in the signupVC;
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(txtUsername.text, forKey: "username")
newUser.setValue(txtPassword.text, forKey: "password")
newUser.setValue(txtEmailAdd.text, forKey: "email")
do {
try context.save()
} catch {}
print(newUser)
print("Object Saved.")
This is the code in the LoginVC;
#IBAction func signinTapp(sender: UIButton) {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "username = %#", "" + txtUsername.text!)
let results:NSArray = try! context.executeFetchRequest(request)
if(results.count > 1){
let res = results[0] as! NSManagedObject
txtUsername.text = res.valueForKey("username") as! String
txtPassword.text = res.valueForKey("password") as! String
//for res in results {
// print(res)
}else{
print("Incorrect username and password")
}
}
Can anyone please advise my the best way forward? - I just need to retrieve the saved core data and check if it matches.
Here is my Core Data model:
look into below code
func CheckForUserNameAndPasswordMatch (userName : String, password : String) ->Bool
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var managedObjectContext = appDelegate.managedObjectContext
var predicate = NSPredicate (format:"userName = %#" ,userName)
var fetchRequest = NSFetchRequest ( entityName: "UserEntity")
fetchRequest.predicate = predicate
var error : NSError? = nil
var fetchRecult = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error)
if fetchRecult?.count>0
{
var objectEntity : UserEntity = fetchRecult?.first as! UserEntity
if objectEntity.userName == userName && objectEntity.password == password
{
return true // Entered Username & password matched
}
else
{
return false //Wrong password/username
}
}
else
{
return false
}
}
Moreover it would not be good to save password in device if you are working on any enterprise product.
import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var txt_username: UITextField!
#IBOutlet var txt_password: UITextField!
var result = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Log_in(_ sender: Any)
{
if txt_username.text == "" && txt_password.text == ""
{
let alert = UIAlertController(title: "Information", message: "Please enter all the fields", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else
{
self.CheckForUserNameAndPasswordMatch(username : txt_username.text! as String, password : txt_password.text! as String)
}
}
func CheckForUserNameAndPasswordMatch( username: String, password : String)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "LoginDetails")
let predicate = NSPredicate(format: "username = %#", username)
fetchrequest.predicate = predicate
do
{
result = try context.fetch(fetchrequest) as NSArray
if result.count>0
{
let objectentity = result.firstObject as! LoginDetails
if objectentity.username == username && objectentity.password == password
{
print("Login Succesfully")
}
else
{
print("Wrong username or password !!!")
}
}
}
catch
{
let fetch_error = error as NSError
print("error", fetch_error.localizedDescription)
}
}
}
Registration page
==================>
import UIKit
import CoreData
class RegistrationPage: UIViewController, UITextFieldDelegate {
#IBOutlet var txt_user: UITextField!
#IBOutlet var txt_mailid: UITextField!
#IBOutlet var txt_pwd: UITextField!
#IBOutlet var txt_cpwd: UITextField!
#IBOutlet var txt_phone: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func register(_ sender: Any)
{
if txt_user.text == "" || txt_mailid.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == ""
{
let alert = UIAlertController(title: "Information", message: "Its Mandatort to enter all the fields", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else if (txt_pwd.text != txt_cpwd.text)
{
let alert = UIAlertController(title: "Information", message: "Password does not match", preferredStyle: .alert
)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let new_user = NSEntityDescription.insertNewObject(forEntityName: "LoginDetails", into: context)
new_user.setValue(txt_user.text, forKey: "username")
new_user.setValue(txt_mailid.text, forKey: "mailid")
new_user.setValue(txt_pwd.text, forKey: "password")
new_user.setValue(txt_phone.text, forKey: "phone")
do
{
try context.save()
print("Registered Sucessfully")
}
catch
{
let Fetcherror = error as NSError
print("error", Fetcherror.localizedDescription)
}
}
self.navigationController?.popViewController(animated: true)
}
}
Is username unique as per database constraint? Then, you will never get more than one result from the fetch.
If you use
if let user = results.first where
user.pass == (passField.text ?? "") {
// login
}
else {
// no login
}
you'd be better of.
Also, do not set the field's from the db; check if they are equal.
Also, please realize that such a sign-up will be valid only on a per-app-installation basis.
For production security, store only hashes of passwords.
It is very simple to make a user login system using core data
First you have to create a project and include core data in it. Then you have to add to the .xcdatamodeld file an entity with some attributes.
Here is a picture of how does the file looks like:
CoreData.xcdatamodeld File
Here is the example code:
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
newUser.setValue("Joe", forKey: "username")
newUser.setValue("JoeTheLazy", forKey: "password")
newUser.setValue(48, forKey: "age")
do {
try context.save()
print("saved")
} catch {
print ( "Some Error has been Detected")
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
let reusutls = try context.fetch(request)
if reusutls.count > 0 {
for r in reusutls as! [NSManagedObject]
{
if let username = r.value(forKey: "username") as? String
{print(username)}
}
}
else {print("Cannot fetch results")
}
}
catch {
print("error")
}
}
#IBOutlet weak var usrName: UITextField!
#IBOutlet weak var passWord: UITextField!
#IBOutlet weak var showList: UILabel!
#IBOutlet weak var errorText: UILabel!
#IBAction func tryLogin(_ sender: UIButton) {
let x = usrName.text
let y = passWord.text
if (x! == "" || y! == "")
{
print ("I am here")
errorText.text = "user name or password empty "
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.predicate = NSPredicate(format: "username = %#", usrName.text!)
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
let passwordFromData = data.value(forKey: "password") as! String
if y! == passwordFromData
{
errorText.text = " You have been Granted Access!"
}
}
}catch {
print("Failed")
}
}
#IBAction func ShowData(_ sender: UIButton) {
var listTprint = ""
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
let reusutls = try context.fetch(request)
if reusutls.count > 0 {
for r in reusutls as! [NSManagedObject]
{
if let username = r.value(forKey: "username") as? String
{listTprint.append(username)
listTprint.append(" ")
let password = r.value(forKey: "password") as? String
listTprint.append(password!)
listTprint.append(" ")
}
}
}
else
{print("Cannot fetch results")}
}
catch {
print("Error")
}
showList.text! = listTprint
}
Coredata save fetch update delete
==================================>
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var my_table: UITableView!
var playerdata = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let fetch_data = NSFetchRequest<NSManagedObject>(entityName: "PlayerDetails")
do
{
self.playerdata = try context.fetch(fetch_data as! NSFetchRequest<NSFetchRequestResult>) as! NSMutableArray
}
catch let error as NSError
{
print(error.localizedDescription)
}
self.my_table.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return playerdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = my_table.dequeueReusableCell(withIdentifier: "hari") as! TableViewCell123
let playerdetails = self.playerdata[indexPath.row]
cell.playername.text = (playerdetails as AnyObject) .value(forKey: "player_name")as? String
cell.playerid.text = (playerdetails as AnyObject) .value(forKey: "player_id")as? String
cell.playerteam.text = (playerdetails as AnyObject) .value(forKey: "player_team")as? String
cell.playerimage.image = UIImage(data: ((playerdetails as AnyObject) .value(forKey: "player_img")as? Data)!)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
self.performSegue(withIdentifier: "datapass", sender: self)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
if(editingStyle == .delete)
{
let user = self.playerdata[indexPath.row] as! NSManagedObject
context.delete(user)
do
{
try context.save()
self.playerdata.removeObject(at: indexPath.row)
my_table.deleteRows(at: [indexPath], with: .fade)
}
catch let error as NSError
{
print("error",error.localizedDescription)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "datapass"
{
let vc2 = segue.destination as! ViewController2
let index = my_table.indexPathForSelectedRow
let data = self.playerdata[(index?.row)!]
vc2.dataupdate = data as! NSManagedObject
}
}
}
VIEWCONTROLLER - 2
===================>
import UIKit
import CoreData
class ViewController2: UIViewController
{
#IBOutlet var txt_playername: UITextField!
#IBOutlet var txt_playerid: UITextField!
#IBOutlet var txt_playerteam: UITextField!
#IBOutlet var img_playerimage: UIImageView!
var dataupdate = NSManagedObject()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if (dataupdate != nil)
{
txt_playername.text = dataupdate.value(forKey: "player_name")as? String
txt_playerid.text = dataupdate.value(forKey: "player_id")as? String
txt_playerteam.text = dataupdate.value(forKey: "player_team")as? String
img_playerimage.image = UIImage(data: dataupdate.value(forKey: "player_img") as! Data)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func save_update(_ sender: Any)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
if (dataupdate != nil)
{
dataupdate.setValue(self.txt_playername.text, forKey: "player_name")
dataupdate.setValue(self.txt_playerid.text, forKey: "player_id")
dataupdate.setValue(self.txt_playerteam.text, forKey: "player_team")
let img_data = UIImageJPEGRepresentation(self.img_playerimage.image!, 1.0)
dataupdate.setValue(img_data, forKey: "player_img")
}
else
{
let newplayer = NSEntityDescription.insertNewObject(forEntityName: "PlayerDetails", into: context)
newplayer.setValue(self.txt_playername.text, forKey: "player_name")
newplayer.setValue(self.txt_playerid.text, forKey: "player_id")
newplayer.setValue(self.txt_playerteam.text, forKey: "player_team")
let img_data = UIImageJPEGRepresentation(self.img_playerimage.image!, 1.0)
newplayer.setValue(img_data, forKey: "player_img")
}
do
{
try context.save()
}
catch let error as NSError
{
print(error.localizedDescription)
}
self.dismiss(animated: true, completion: nil)
}
}
I get objects array from core data:
lazy var managedObjectContext : NSManagedObjectContext? = {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
return managedObjectContext
}
else {
return nil}
}()
var tests=[Test]()
func fetchLog() {
let fetchRequest = NSFetchRequest(entityName: "Test")
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Test] {
tests = fetchResults
}
And then tray to update it:
managedObjectContext?.updatedObjects(tests[atRow] as NSManagedObject)
But get error: '(NSManagedObject) -> $T5' is not identical to 'NSSet'
Whats wrong?
NSManagedObject is registered with NSManagedObjectContext(MOC). To update it, call MOC's save().
like this:
let aTest = test[atRow] as Test
// update through properties like aTest.id = 2
...
// and save
var error: NSError?
if managedObjectContext!.save(&error) {
println("saved successfully")
} else {
println("failed to save")
if let saveError = error {
println("error=\(saveError.localizedDescription)")
}
}