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()
}
}
Related
Goal:
My goal is to pass the current minimum, average and maximum value data to table view and present them to the user.
Error:
When I hit the "Save" button "nan" value is passed with the current minimum, average and maximum value data.
UI screenshot
Here is the table view before pressing the Save button
Here is the table view after pressing the Save button
Here is the current code:
Record.swift
import Foundation
import CoreData
class Record: NSManagedObject {
var minimumValue: Float = .nan
var averageValue: Float = .nan
var maximumValue: Float = .nan
}
RecordTableViewController.swift
class RecordCell: UITableViewCell {
#IBOutlet weak var maximumValueLabel: UILabel!
#IBOutlet weak var averageValueLabel: UILabel!
#IBOutlet weak var minimumValueLabel: UILabel!
}
class RecordTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
private lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "History")
let sortDescriptor: [NSSortDescriptor] = []
fetchRequest.sortDescriptors = sortDescriptor
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}()
let cellIdentifier: String = "cellID"
var recordsArray = [Record]()
override func viewDidLoad() {
super.viewDidLoad()
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight(_:)))
swipe.direction = .right
self.view.addGestureRecognizer(swipe)
recordsArray = fetchAllRecords()
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .delete:
let removedRecord = fetchedResultsController.object(at: indexPath) as! NSManagedObject
let context = fetchedResultsController.managedObjectContext
context.delete(removedRecord)
do {
try context.save()
self.recordsArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} catch _ {
}
default:
break
}
}
}
extension RecordTableViewController {
public func fetchAllRecords() -> [Record] {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "History")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
return result as! [Record]
} catch let error {
fatalError(error.localizedDescription)
}
}
}
MainViewController.swift
import UIKit
import Dispatch
import CoreData
import Accelerate
import Foundation
import UserNotifications
class MainViewController: UIViewController {
var minimum: Float = .nan
var average: Float = .nan
var maximum: Float = .nan
var decibel: Float = .nan
/// MARK: Segue functions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "saveRecord" {
let recordVC = segue.destination as! RecordTableViewController
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let record = Record.init(entity: NSEntityDescription.entity(forEntityName: "History", in: context)!, insertInto: context)
record.minimumValue = Float(minDbLabel.text!) ?? 0.0
record.averageValue = Float(averageDbLabel.text!) ?? 0.0
record.maximumValue = Float(maximumDbLabel.text!) ?? 0.0
saveNewRecord(record: record)
self.recordsArray.append(record)
recordVC.recordsArray = self.recordsArray
}
}
#IBAction func save(_ sender: UIButton){
self.performSegue(withIdentifier: "saveRecord", sender: nil)
}
// MARK: Core Data functions
private func saveNewRecord(record: Record) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
var index: Int = 0
let entity = NSEntityDescription.entity(forEntityName: "History", in: context)
let newRecord = [NSManagedObject(entity: entity!, insertInto: context)] as [NSManagedObject]
newRecord[index].setValue(record.minimumValue, forKey: "minimumValue")
newRecord[index].setValue(record.averageValue, forKey: "averageValue")
newRecord[index].setValue(record.maximumValue, forKey: "maximumValue")
index += 1
do {
try context.save()
} catch let error {
print("\(error.localizedDescription)")
}
}
}
Any help is appreciated.
The code you provided is kinda confusing, however, here's how I setup my CoreData applications.
First: I create a CoreDataManager model
This will handle all of my Model functions like fetching viewing and context etc...
struct CoreDataManager {
static let shared = CoreDataManager()
let persistentContainer: NSPersistentContainer = {
let perCon = NSPersistentContainer(name: "EntityName")
perCon.loadPersistentStores { (storeDescription, err) in
if let err = err {
fatalError("\(err)")
}
}
return perCon
}()
func fetchEntitys() -> [Entity] {
let context = persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Entity>(entityName: "EntityName")
do {
let entity = try context.fetch(fetchRequest)
return entity
} catch let err {
print("\(err)")
return []
}
}
func resetEntitys() {
let context = persistentContainer.viewContext
let batchRequest = NSBatchDeleteRequest(fetchRequest: Entity.fetchRequest())
do {
try context.execute(batchRequest)
} catch let err {
print("\(err)")
}
}
}
Second: Setup your secondViewController the viewController in which you create the objects in
You would need to create a delegate for this viewController
protocol CreateControllerDelegate: class {
func didAdd(entity: Entity)
}
In your secondViewController in this case, it's CreateController you should add the following property.
weak var delegate: CreateControllerDelegate?
Implement the function in which you will save objects into your CoreData.
func createEntity() {
let context = CoreDataManager.shared.persistentContainer.viewContext
let entity = NSEntityDescription.insertNewObject(forEntityName: "EntityName", into: context)
entity.setValue(nameTextField.text, forKey: "name")
// set all of your values that you want to be saved.
do {
try context.save()
dismiss(animated: true) {
self.delegate?.didAdd(entity: entity as! Entity)
}
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
Finally, setup your firstViewController the one in which you will display all of your Core Data objects.
Add a property to your MainController in which it will hold all of your Entity objects.
var objectsArray = [Entity]()
Inside of your MainController's viewDidLoad function add the following.
override func viewDidLoad() {
super.viewDidLoad()
self.objectsArray = CoreDataManager.shared.fetchEntitys()
}
Confirm and implement the CreateControllerDelegate in your MainController.
extension MainController: CreateControllerDelegate {
func didAdd(entity: Entity) {
objectsArray.append(entity)
let indexPath = IndexPath(row: objectsArray.count - 1, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
Push your secondViewController.
I don't use Segues.
#IBAction func handleAdd(_ sender: Any) {
let createController = storyboard?.instantiateViewController(withIdentifier: "CreateController") as! CreateController
createController.delegate = self
let navController = UINavigationController(rootViewController: createController)
navController.modalPresentationStyle = .fullScreen
present(navController, animated: true)
}
I hope this is helpful and if there's something that's not working let me know!
Good Luck!
I created a pagination tool from a toolbar that hits this method :
func nextPage(sender: UIBarButtonItem) {
let currentChapter = page.valueForKey("chapter") as! Int
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Page")
fetchRequest.predicate = NSPredicate(format: "(chapter = %d)", currentChapter + 1)
do {
let result = try managedContext.executeFetchRequest(fetchRequest)
// It is here, I can clearly see we have the old object.
self.page = result[0] as! NSManagedObject
// And here I can clearly see that a new object was set.
self.tableView.reloadData()
self.view.setNeedsDisplay()
} catch {
let fetchError = error as NSError
print(fetchError)
}
}
This method is located in my UIViewController that is set up like so :
import UIKit
import CoreData
class PageViewController: UIViewController, UITableViewDelegate, UINavigationBarDelegate, UITableViewDataSource {
// Mark: Properties
var page: NSManagedObject!
var tableView = UITableView()
var toolBar = UIToolbar()
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height - 50)
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
tableView.scrollEnabled = true
tableView.userInteractionEnabled = true
tableView.delegate = self
tableView.dataSource = self
tableView.tableHeaderView = containerView
self.view.addSubview(tableView)
Any ideas why my tableView is not reloading its new data?
Update
As recommended by #Koder and #Simon, I updated my code as so.. but the UI still did not update :
func nextPage(sender: UIBarButtonItem) {
let currentChapter = page.valueForKey("chapter") as! Int
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Page")
fetchRequest.predicate = NSPredicate(format: "(chapter = %d)", currentChapter + 1)
do {
let result = try managedContext.executeFetchRequest(fetchRequest)
self.page = result[0] as! NSManagedObject
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.view.setNeedsDisplay()
}
} catch {
let fetchError = error as NSError
print(fetchError)
}
}
Per LucaD's recommendation, I'll also include my numberOfRows and numberOfSections :
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.total
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
You should fire all the UI refreshing code on the main thread.
For updating tableView, try firing the below from the background thread:
dispatch_async(dispatch_get_main_queue())
{
self.tableView.reloadData()
}
this code block will asynchronously get executed on the main thread.
I suspect you need to move that code into the main thread: UI changes performed in background threads won't update the screen. Try this:
dispatch_async(dispatch_get_main_queue())
{
self.tableView.reloadData()
self.view.setNeedsDisplay()
}
Simon
So, I'm struggling to learn how to handle CoreData properly.
Here is my code:
import UIKit
import CoreData
class IngredientsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController?
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchIngredients(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController?.delegate = self
fetchedResultsController?.performFetch(nil)
}
func fetchIngredients() -> NSFetchRequest {
var fetchRequest = NSFetchRequest(entityName: "DetailsForRecipe")
let sortDescriptor = NSSortDescriptor(key: "ingredients", ascending: true)
fetchRequest.predicate = nil
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
return fetchRequest
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ingCell", forIndexPath: indexPath) as! UITableViewCell
if let ingCell = fetchedResultsController?.objectAtIndexPath(indexPath) as? DetailsForRecipe {
cell.textLabel?.text = ingCell.ingredients
}
return cell
}
}
and
import UIKit
import CoreData
class SingleIngredientViewController: UIViewController {
#IBOutlet var ingField: UITextField!
var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func addIng(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("DetailsForRecipe", inManagedObjectContext: moc!)
let details = DetailsForRecipe(entity: entityDescription!, insertIntoManagedObjectContext: moc)
details.ingredients = ingField.text
var error: NSError?
moc?.save(&error)
if let err = error {
var status = err.localizedFailureReason
println(status)
} else {
println("Ingredient \(ingField.text) saved successfully!")
}
if let navigation = navigationController {
navigation.popViewControllerAnimated(true)
}
}
}
My model:
import Foundation
import CoreData
class DetailsForRecipe: NSManagedObject {
#NSManaged var name: String
#NSManaged var ingredients: String
#NSManaged var image: NSData
}
The app should insert the ingredient name in the text field, save it into coreData, then it should be retrieved in the table view. When I text the ingredient name and press "add", the prinln message says it was successfully saved, but the table view does not update.
What am I doing wrong here? I'm not a developer, I've read many tutorials on how to do this, but it is very confusing! So forgive me about this.
Thanks in advance!
I haven't read your full source code, but by doing an immediate glance, I don't see that you've called the tableview's reloadData function. If you don't have an IBOutlet set up for your table view, you will want to do that and then call reloadData() on it.
Call reloadData() on your table view after the change is made.
my app is very simple: I have one tableview to store recipe *names and, for each recipe name, another tableview with several *ingredients for each recipe.
I already managed to save the name and the ingredients with CoreData, but here is the problem: when I press to add a NEW recipe name and enter the ingredients table view area, the ingredients saved for the previous recipe are there! How do I clear the table view to start a new one?
Also, my table views does not get updated immediately, I have to close the app and open it again. How do I fix it?
Note: If my question is too hard to understand, I can post some code! Thanks in advance, everyone =)
EDIT
code:
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
#IBOutlet var tableView: UITableView!
var imageList: [UIImage] = []
var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController?
override func viewDidLoad() {
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchName(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController?.delegate = self
fetchedResultsController?.performFetch(nil)
tableView.reloadData()
}
func fetchName() -> NSFetchRequest {
var fetchRequest = NSFetchRequest(entityName: "Details")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.predicate = nil
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
return fetchRequest
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("recipeCell", forIndexPath: indexPath) as! UITableViewCell
if let recipeCell = fetchedResultsController?.objectAtIndexPath(indexPath) as? Details {
cell.textLabel?.text = recipeCell.name
}
return cell
}
}
-
import UIKit
import CoreData
class InfoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate {
#IBOutlet var nameField: UITextField!
#IBOutlet var imageView: UIImageView!
var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
//Pick the image by tap
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
tapGestureRecognizer.numberOfTapsRequired = 1
imageView.addGestureRecognizer(tapGestureRecognizer)
imageView.userInteractionEnabled = true
}
//Pick the image by tapping, accessing the photoLibrary
func chooseImage(recognizer: UITapGestureRecognizer) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
//Put the selected image into the screen
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject:AnyObject]) {
let pickedImage: UIImage = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
// small picture
let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(288,148))
var sizeOfImageView:CGRect = imageView.frame
sizeOfImageView.size = smallPicture.size
imageView.frame = sizeOfImageView
imageView.image = smallPicture
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
func scaleImageWith(image:UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRectMake(0,0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
#IBAction func addButton(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("Details", inManagedObjectContext: moc!)
let details = Details(entity: entityDescription!, insertIntoManagedObjectContext: moc)
details.name = nameField.text
var error: NSError?
moc?.save(&error)
if let err = error {
var status = err.localizedFailureReason
println("\(status)")
} else {
println("Ingredient \(nameField.text) saved successfully!")
}
if let navigation = navigationController {
navigation.popViewControllerAnimated(true)
}
}
}
-
import UIKit
import CoreData
class IngredientListViewController: UIViewController, NSFetchedResultsControllerDelegate {
#IBOutlet var tableView: UITableView!
var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController?
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchIngredient(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController?.delegate = self
fetchedResultsController?.performFetch(nil)
tableView.reloadData()
}
func fetchIngredient() -> NSFetchRequest {
var fetchRequest = NSFetchRequest(entityName: "Ingredients")
let sortDescriptor = NSSortDescriptor(key: "ingredients", ascending: true)
fetchRequest.predicate = nil
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
return fetchRequest
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ingCell", forIndexPath: indexPath) as! UITableViewCell
if let recipeCell = fetchedResultsController?.objectAtIndexPath(indexPath) as? Ingredients {
cell.textLabel?.text = recipeCell.ingredients
}
return cell
}
}
-
import UIKit
import CoreData
class IngredientViewController: UIViewController {
#IBOutlet var nameField: UITextField!
var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func addButton(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("Ingredients", inManagedObjectContext: moc!)
let details = Ingredients(entity: entityDescription!, insertIntoManagedObjectContext: moc)
details.ingredients = nameField.text
var error: NSError?
moc?.save(&error)
if let err = error {
var status = err.localizedFailureReason
println("\(status)")
} else {
println("Ingredient \(nameField.text) saved successfully!")
}
if let navigation = navigationController {
navigation.popViewControllerAnimated(true)
}
}
}
and models:
import Foundation
import CoreData
class Ingredients: NSManagedObject {
#NSManaged var ingredients: String
#NSManaged var relationship: NSSet
}
import Foundation
import CoreData
class Details: NSManagedObject {
#NSManaged var name: String
#NSManaged var relationship: Ingredients
}
In outline:
You need to amend your model: currently each Details object can have only one Ingredients. I suspect you need this relationship to be "to many" so a recipe can have many ingredients.
You need to add a var (of type Details?) to your IngredientListViewController. This will represent the chosen Recipe. (eg. var chosenRecipe : Details?)
In fetchIngredient, you need to add a predicate to the fetch, to limit the results to the chosen recipe. eg. fetch.predicate = NSPredicate(format:"ANY relationship == %#", chosenRecipe)
Before segueing to this VC, you need to set the chosenRecipe (probably in prepareForSegue, or didSelectRowAtIndexPath in the preceding table view).
To get your TV to update automatically, use the fetchedResultsController delegate methods. (Have you implemented these?)
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