So, this is my code:
ViewController 1 :
class ViewSet: UIViewController {
#IBOutlet var Label_1: UILabel!
#IBOutlet var Label_2: UILabel!
#IBOutlet var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "TestingCoreData")
request.returnsObjectsAsFaults = false;
var results: NSArray = moc.executeFetchRequest(request, error: nil)!
if (results.count > 0) {
var res = results[0] as! NSManagedObject
Label_1.text = res.valueForKey("label_1") as? String
Label_2.text = res.valueForKey("label_2") as? String
Text.text = res.valueForKey("text") as? String
} else {
println("No results found")
}
}
}
ViewController 2:
import UIKit
import CoreData
class Label_1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var Label_1: UITextField!
#IBAction func addLabel_1(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var label1 = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
label1.setValue("\(Label_1.text)", forKey: "label_1")
moc.save(nil)
println("Object saved")
performSegueWithIdentifier("toLabel2", sender: self)
}
}
ViewController 3:
import UIKit
import CoreData
class Label_2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var Label_2: UITextField!
#IBAction func add(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var label2 = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
label2.setValue("\(Label_2.text)", forKey: "label_2")
moc.save(nil)
println("Object saved")
performSegueWithIdentifier("toText", sender: self)
}
}
ViewController 4:
import UIKit
import CoreData
class Text: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var Text: UITextView!
#IBAction func done(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var text = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
text.setValue("\(Text.text)", forKey: "text")
moc.save(nil)
println("Object saved")
navigationController?.popToRootViewControllerAnimated(true)
}
}
I believe the code is very simple. I'm trying to learn my way through CoreData, but I can't seem to properly make it work.
It crashes here, when I press add to go to the 3rd view controller:
Can anyone help me? I'm new to this stuff! Thanks in advance
Related
How can i passing data uiviewController from uiview
I am Using function but it was not working
protocol name is startcalldelegate and function name is startcall
UIView Code
protocol StartCallDelegate: class {
func startCall(localNickname :String, remoteNickname :String)}
class CardView: UIView {
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
weak var delegate: CardViewDelegate?
weak var socketdelegate: StartCallDelegate?
#IBOutlet weak var UserPhoto: UIImageView!
#IBOutlet weak var UserNickName: UILabel!
#IBOutlet weak var UserAge: UILabel!
#IBOutlet weak var UserPeople: UILabel!
var localNickname: String = ""
var remoteNickname: String = ""
#IBAction func SendMessage(_ sender: Any) {
print("SendMessage")
//print(localNickName)
//print(UserNickName.text!)
}
#IBAction func SendVideoCall(_ sender: Any) {
print("SendVideoCall")
let entityDescription = NSEntityDescription.entity(forEntityName: "Profile", in: managedObjectContext)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDescription
do {
let objects = try managedObjectContext.fetch(request)
if objects.count > 0 {
let match = objects[0] as! NSManagedObject
localNickname = match.value(forKey: "nick") as! String
} else {
print("Nothing founded")
}
} catch {
print("error")
}
remoteNickname = UserNickName.text!
socketdelegate?.startCall(localNickname: localNickname, remoteNickname: remoteNickname)
delegate?.VideoChatSegue()
}
}
UIViewcontroller Code
class ViewController: UIViewcontroller, StartCallDelegate {
var localNickname: String = ""
var remoteNickname: String = ""
override func viewDidLoad() {
super.viewDidLoad()
print(localNickname)
print(remoteNickname)
}
func startCall(localNickname: String, remoteNickname: String) {
print("Action startcall func")
self.localNickname = localNickname
self.remoteNickname = remoteNickname
}
startCall func not working
You need to define delegate in viewcontroller' ViewDidLoad
let objOardView = CardView() // this is only test purpose
objOardView.socketdelegate = self
My app crashes every time using the abort function- core data. It crashes because of this code. What is wrong with it?
import UIKit
import CoreData
class MyWordsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var myList: Array<AnyObject> = []
override func viewDidLoad() {
super.viewDidLoad()
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
let freq = NSFetchRequest(entityName: "List")
do {
try myList = context.executeFetchRequest(freq)
} catch {
print("error")
}
tableView.reloadData()
Delegate for tableview are not added in your code.
Add these in your view controller
class MyWordsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
Add this code in your viewDidLoad
self.Tablename.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
Tablename.dataSource = self
Tablename.delegate = self
searchBar.delegate = self
For core data try the following code
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
var fetchRequest = NSFetchRequest(entityName: "List")
if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
if fetchResults.count != 0{
println(fetchResults)
}
}
Try this, worked for me (swift 2 Xcode 7 beta 5): (I did changes to fit your code)
import UIKit
import CoreData
var myList: Array<AnyObject> = []
class MyWordsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
}
override func viewDidAppear(animated:Bool)
{
//reference to app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//reference NSManaged object context
let context: NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "List")
do
{
try myList = context.executeFetchRequest(freq)
NSLog("Number of rows (App): \(myList.count)")
} catch _ { NSLog("That went badly...") }
tableView.reloadData()
}
}
I have spent a lot of time researching this problem and have not found any help relevant to the matter, so I am hoping this is not a fool's errand. I am developing an app with a core data model where I want the user to perform a search in one screen of the core data, and be able to select which records from the search result are stored in the table view. Every tutorial I have found assumes that I want every record in core data automatically displayed in the table view. At this point I believe I have all of the core data code, and much of the table view code implemented as I would desire. The only thing I want to change is allowing the user to search the core data, and choose which records to display in the table view. The first code snippet I have below is of the table view controller I have to display the core data, and the code following that is the code for the view controller I am using to save, find, and eventually select core data to be displayed. Thank you in advance for your help.
`import Foundation
import UIKit
import CoreData
class PatientViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
func taskFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Patients")
let sortDescriptor = NSSortDescriptor(key: "lastname", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
var patients = [Patients]()
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let numberOfSections = fetchedResultController.sections?.count
return numberOfSections!
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
return numberOfRowsInSection!
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MyCellTwo", forIndexPath: indexPath) as! UITableViewCell
let patient = fetchedResultController.objectAtIndexPath(indexPath) as! Patients
cell.textLabel?.text = patient.lastname + ", " + patient.firstname
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
managedObjectContext?.deleteObject(managedObject)
managedObjectContext?.save(nil)
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.reloadData()
}
}`
And the second bit of code.
import UIKit
import CoreData
class AddPatientViewController: UIViewController {
#IBOutlet weak var socialSecurityNumber: UITextField!
#IBOutlet weak var lastName: UITextField!
#IBOutlet weak var firstName: UITextField!
#IBOutlet weak var middleInitial: UITextField!
#IBOutlet weak var streetAddress: UITextField!
#IBOutlet weak var apartment: UITextField!
#IBOutlet weak var city: UITextField!
#IBOutlet weak var state: UITextField!
#IBOutlet weak var zipCode: UITextField!
#IBOutlet weak var homePhone: UITextField!
#IBOutlet weak var cellPhone: UITextField!
#IBOutlet weak var workPhone: UITextField!
#IBOutlet weak var mrn: UILabel!
#IBOutlet weak var primaryDiagnosis: UITextField!
#IBAction func savePatient(sender: AnyObject) {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newPatient = NSEntityDescription.insertNewObjectForEntityForName("Patients", inManagedObjectContext: context) as! NSManagedObject
newPatient.setValue(firstName.text, forKey: "firstname")
newPatient.setValue(lastName.text, forKey: "lastname")
newPatient.setValue(socialSecurityNumber.text, forKey: "ssn")
newPatient.setValue(cellPhone, forKey: "cellphone")
/*newPatient.setValue(middleInitial.text, forKey: "middileinitial")
newPatient.setValue(streetAddress, forKey: "streetaddress")
newPatient.setValue(apartment, forKey: "apartment")
newPatient.setValue(city, forKey: "city")
newPatient.setValue(state, forKey: "state")
newPatient.setValue(zipCode, forKey: "zipcode")
newPatient.setValue(homePhone, forKey: "homephone")
newPatient.setValue(workPhone, forKey: "workphone")
newPatient.setValue(primaryDiagnosis, forKey: "primarydiagnosis")*/
context.save(nil)
println(newPatient)
println("Object Saved.")
}
#IBAction func findPatient(sender: AnyObject) {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Patients")
request.returnsObjectsAsFaults = false;
request.predicate = NSPredicate(format: "lastname = %#", lastName.text)
var results:NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0) {
var res = results[0] as! NSManagedObject
lastName.text = res.valueForKey("lastname") as! String
firstName.text = res.valueForKey("firstname") as! String
socialSecurityNumber.text = res.valueForKey("ssn") as! String
//for res in results{
// println(res)
//}
} else {
println("0 Results Returned...Potential Error")
}
}
#IBAction func selectPatient(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
I have a custom NSManagedObject:
import Foundation
import CoreData
#objc(Article)
class Article: NSManagedObject {
#NSManaged var articleID: String
#NSManaged var isFavorite: Bool
init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?, articleID: String, isFavorite: Bool) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
self.articleID = articleID
self.isFavorite = isFavorite
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
}
But I got error when I trie to add a new entry to CoreData:
let articleEntity = NSEntityDescription.entityForName("Article", inManagedObjectContext: self.context!)
let newArticle = Article(entity: articleEntity!, insertIntoManagedObjectContext: self.context!)
newArticle.articleID = articleID
newArticle.isFavorite = true
Use of unresolved identifier 'Article'
From the information above, it looks like you have't added the class for the entity in configuration of the coredata. Make sure you have mapped class against entity in the configuration of .xcdatamodeld file. You can check the below example.
// 1) Swift File
import Foundation
import CoreData
import UIKit
class DatabaseHelper{
static var shareInstance = DatabaseHelper()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
func save(object:[String:String]){
let student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context!) as! Student
student.name = object["name"]
student.address = object["address"]
student.city = object["city"]
student.mobile = object["mobile"]
do{
try context?.save()
}catch{
print("Data is not save")
}
}
func getStudentData() -> [Student]{
var student = [Student]()
let fatchRequest = NSFetchRequest<NSManagedObject>(entityName: "Student")
do{
student = try context?.fetch(fatchRequest)as![Student]
}catch{
print("can not get Data")
}
return student
}
// 2) view Controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtCity: UITextField!
#IBOutlet weak var txtMobile: UITextField!
#IBOutlet weak var txtAddress: UITextField!
#IBOutlet weak var txtName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func btnSaveData(_ sender: Any) {
var dict = ["name":txtName.text,"address":txtAddress.text,"city":txtCity.text,"mobile":txtMobile.text]
DatabaseHelper.shareInstance.save(object: dict as! [String : String])
}
#IBAction func btnShowAction(_ sender: Any) {
let show = storyboard?.instantiateViewController(withIdentifier: "AnotherViewController")as! AnotherViewController
self.navigationController?.pushViewController(show, animated: true)
}
}
// 3) Data get in table View
import UIKit
class AnotherViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
#IBOutlet weak var tblView: UITableView!
var student = [Student]()
override func viewDidLoad() {
super.viewDidLoad()
student = DatabaseHelper.shareInstance.getStudentData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return student.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tblView.dequeueReusableCell(withIdentifier: "tblCell", for: indexPath)as! tblCell
cell.lblName.text = student[indexPath.row].name
cell.lblAddress.text = student[indexPath.row].address
cell.lblCity.text = student[indexPath.row].city
cell.lblMobile.text = student[indexPath.row].mobile
return cell
}
}
class tblCell : UITableViewCell{
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var lblAddress: UILabel!
#IBOutlet weak var lblCity: UILabel!
#IBOutlet weak var lblMobile: UILabel!
}
// 4) AppViewController
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("Document Directory:", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not found!!")
return true
}
I'm trying to update an attribute in Core Data and then display it. However, when I tell the program to display it, it displays the original value.
Based off the code below, username is set to a String. I know 100% that username is saved into Core Data. However, when I try to update it, it saves to Core Data, but prints out the old value. How can I print out only the "newest" value?
import UIKit
import CoreData
class NameSettings: UIViewController {
#IBOutlet var nameText: UITextField!
var userID: String!
var username: String!
override func viewDidLoad() {
super.viewDidLoad()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var res = results [0] as NSManagedObject
userID = res.valueForKey("userID") as String
username = res.valueForKey("username") as String
println(username)
nameText.text = username
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func saveTapped(sender: AnyObject) {
//println(userID)
var query = PFQuery(className:"_User")
query.getObjectInBackgroundWithId(userID) {
(update1: PFObject!, error: NSError!) -> Void in
if error == nil {
update1["username"] = self.nameText.text
update1.saveEventually()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var updateUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
updateUser.setValue(self.nameText.text, forKey: "username")
context.save(nil)
//println(self.nameText.text)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
}
NOTE: All the println's are just for debugging.
As your code stands now, you're not overwriting any NSManagedObject; you're inserting a new one, i.e. insertNewObjectForEntityForName.
Instead, what you can do is declare the NSManagedObject you want to save and the NSManagedObjectContext you want to save to as global variables; then simply set a new value for the NSManagedObject's relevant key before saving to the NSManagedObjectContext, ex:
var userID: String!
var username: String!
var res : NSManagedObject!
var context : NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
//...
context = appDel.managedObjectContext! // <-- Use global var
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
res = results [0] as NSManagedObject // <-- Use global var
//...
}
#IBAction func saveTapped(sender: AnyObject) {
//println(userID)
var query = PFQuery(className:"_User")
query.getObjectInBackgroundWithId(userID) {
(update1: PFObject!, error: NSError!) -> Void in
if error == nil {
update1["username"] = self.nameText.text
update1.saveEventually()
res.setValue(self.nameText.text, forKey: "username")
context.save(nil)
//println(self.nameText.text)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}