prepare for segue...with pointers? - arrays

var routes:[PFObject] = [PFObject]()
func getRoutes() {
let query = PFQuery(className: "PoolRoute")
query.includeKey("selectedCustomer")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects as? [PFObject] {
self.routes = objects
self.tableView.reloadData()
these objects have a column named "selectedCustomer" that is full of pointer objects.....I would like to segue to another tableview controller and display the pointer objects from the selected cell...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == "toRoutesDetailVC" {
let nav = segue.destinationViewController as! PoolRouteDetailVC
if let indexPath = self.tableView?.indexPathForSelectedRow {
nav.currentObject = (self.routes[indexPath.row]["selectedCustomer"] as [PFObject])
// '() -> NSIndexPath?' does not have a member named 'row'
//i guess its not the right syntax...not exactly sure how to write the code to get it to send to the array to the detailViewController. thanks in advance!

Related

How to pass value from 2d array with prepareForSegue

I have a array like this in a tableView:
var array: [[String]] = [["Apples", "Bananas", "Oranges"], ["Round", "Curved", "Round"]]
I would like to pass on the name of the cell when the cell is pressed. With a standard array I would do this:
let InfoSegueIdentifier = "ToInfoSegue"
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == InfoSegueIdentifier
{
let destination = segue.destination as! InfoViewController
let arrayIndex = tableView.indexPathForSelectedRow?.row
destination.name = nameArray[arrayIndex!]
}
}
And in the next ViewController (InfoViewController)
var name = String()
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = name
}
Error: "Cannot assign value of type '[String]' to type 'String'"
Change this part of code
if segue.identifier == InfoSegueIdentifier
{
let destination = segue.destination as! InfoViewController
let arrayIndex = tableView.indexPathForSelectedRow?.row
destination.name = nameArray[arrayIndex!]
}
To
if segue.identifier == InfoSegueIdentifier
{
let destination = segue.destination as! InfoViewController
let arrayIndexRow = tableView.indexPathForSelectedRow?.row
let arrayIndexSection = tableView.indexPathForSelectedRow?.section
destination.name = nameArray[arrayIndexSection!][arrayIndexRow!]
}
Try and share the results.
Reason For crash: In your first viewController you have [[String]] which is the datasource for your section. Now, when you try to get the object from this array it will returns you [String] and in your destination viewController you have the object of type String. and while assigning [String] to String it cause the crash with type mismatch. So, what above code does is, it will take first [String] from the arrayIndexSection and then the String from arrayIndexRow and thus pass a String object to destination.
Hope it clears.
You are getting this error because you are passing an array to second view controller and there is a variable of type string. So, replace this method like this.
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == InfoSegueIdentifier
{
let destination = segue.destination as! InfoViewController
if let indexPath = tableView.indexPathForSelectedRow{
destination.name = nameArray[indexPath.section][indexPath.row]
}
}
}

Edit a tableView entry in a separate ViewController an pass back the edited data into the tableView

I am currently programming a diary app. Therefore I have all my entries listed in a tableView. One diary entry consists of a title, date, category and actually the diary content as a string.
All entries are stored in arrays like this:
var array = [Einträge] ()
To edit one entry, the data of one entry is passed to the "DetailViewController" by tapping on the entry in the tableView. I am currently able to change the different data, but i can't pass the changed data back to my tableView.
For showing the entry in the DetailViewController a segue is used:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case "AddEintragSegue":
let destVC = segue.destination as! AddEintragViewController
destVC.delegate = self
case "Show Detail":
let dVC = segue.destination as! DetailViewController
if let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell) {
dVC.eintrag = array[indexPath.row]
}
default: break
}
}
To save the Changes, this button have to be pressed. What should I add to the following Code?
#IBAction func btnSafeChanges(_ sender: Any) {
eintrag = Einträge(name: txtTitel.text!, inhalt: txtInhalt.text!, datum: txtDatum.text!, kategorie: txtKategorie.text!)
Or should I use another type of segue?
You can go with some delegate to pass the data back
import UIKit
struct Einträge {}
protocol DetailViewControllerDelegate: class {
func newEintragCreated(eintrag: Einträge, index: Int)
}
final class InitialViewController: UIViewController {
var array: [Einträge] = []
let tableView = UITableView()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case "Show Detail":
let dVC = segue.destination as! DetailViewController
if let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell) {
dVC.eintrag = array[indexPath.row]
dVC.index = indexPath.row
dVC.newEintragDelegate = self
}
default:
break
}
}
}
}
extension InitialViewController: DetailViewControllerDelegate {
func newEintragCreated(eintrag: Einträge, index: Int) {
// replace old object for newly created one
array[index] = eintrag
tableView.reloadData()
}
}
final class DetailViewController: UIViewController {
var eintrag: Einträge!
var index: Int?
weak var newEintragDelegate: DetailViewControllerDelegate?
func btnSafeChanges() {
let eintrag = Einträge()
if let index = index, let delegate = newEintragDelegate {
delegate.newEintragCreated(eintrag: eintrag, index: index)
}
}
}

Permanent Data with Prepare For Segue

I am currently trying to use Permanent Data and Prepare For Segue together. This is what I have so far: (VC1)
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
}
(VC2):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toSecondViewController" {
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items:[String]
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(textField.text!)
print(items)
} else {
items = [textField.text!]
}
UserDefaults.standard.set(items, forKey: "items")
}
}
I am trying to add an item to an array on VC2. Then I want to transfer the array to VC1 whilst storing it permanently. I am using Xcode 8.0 and Swift 3.0.
Its the other way around; when your source view controller initiates a segue from either a storyboard or performSegue, the source view controller's prepareForSegue method gets invoked. With in that method you should determine the type of view controller you are segueing to and set the properties accordingly. Note that you don't really need the identifier unless you have more than one segue to the same destination in which case its sometimes useful to know which one is being invoked.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let notificationsViewController = segue.destination as? NotificationsViewController {
NotificationsViewController.notification = notification
}
}
Your question only explains.how to pass and store data permanently. But, you haven't mentioned about where you want to save data. I presume,you using tableView to store data and retrieving it.
In AppDelegate applicationDidFinishLaunching register an empty array as default value for the key "NewArray".
let defaultValues = ["NewArray": [String]()]
UserDefaults.standard.register(defaults: defaultValues)
In Second VC define newArray (variable names are supposed to start with a lowercase letter) also as empty String array
var newArray = [String]()
In viewDidLoad retrieve the array from user defaults, append the new item, save the array back to user defaults and reload the table view
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
newArray = defaults.array(forKey: "NewArray") as! [String]
newArray.append(newItem) //newItem is the data.Which you passing from First VC
defaults.set(newArray, forKey: "NewArray")
self.tableView?.reloadData()
}
and you don't need to use segue on your second VC unless you passing data from it...

Permanent Data and Prepare For Segue

I am trying to use Permanent Data and Prepare For Segue together. This is what I have so far in: (View Controller 1)
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
}
in (View Controller 2):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toSecondViewController" {
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items:[String]
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(textField.text!)
print(items)
} else {
items = [textField.text!]
}
UserDefaults.standard.set(items, forKey: "items")
}
}
I am attempting to add an item to an array on VC2. Then I want to transfer the array to VC1 whilst also storing it permanently. Then every time I shut down and reload the app I can print the array. The error message states "Use of unresolved identifier items". I am using Xcode 8.0 and Swift 3.0.
Ok so because you said you want to persist the data over app starts you will need the User Defaults to store your items. As Dan already suggested you are basically doing it right. You just want to set a variable that was not declared before. But I will show you this in the following code. I will also attach a second approach in which the items are passed to next view controller while performing the segue.
First example: Imagine we have two view controllers like in your example. The first view controller contains a UITextField to do user text input. Whenever we switch from the first view controller to the second view controller with the help of a storyboard segue (e.g. when pressing a button) we take the existing texts from previous segues from the User Defaults and add the current user input and then persist it back to the User Defaults. This happens in the first view controller:
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "toSecondViewController" {
let itemsFromDefaults = UserDefaults.standard.object(forKey: "items")
var items: [String]
if let tempItems = itemsFromDefaults as? [String]
{
items = tempItems
items.append(textField.text!)
}
else
{
items = [textField.text!]
}
print(items)
UserDefaults.standard.set(items, forKey: "items")
}
}
}
This first view controller looks pretty similar to your code but I wanted to add it for completeness.
Then in the second view controller we just grab the items from the user defaults and store it directly in a instance variable of this view controller. With the help of this we can do what we want in other methods within the view controller and process the items further. As I said what you were missing was the instance variable declaration to store the items in.
class ViewController2: UIViewController {
private var items: [String]? // This is only accessible privately
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.items = UserDefaults.standard.object(forKey: "items") as? [String]
}
}
Second Example: You could also declare a internal/public variable in ViewController2 so that you can set it directly from the first view controller in perform segue. Than you wouldn´t need to grab the items from the User Defaults in ViewController2. For that you can access the destination view controller of the segue then cast it to ViewController2 and directly set the items of it.
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "toSecondViewController" {
let itemsFromDefaults = UserDefaults.standard.object(forKey: "items")
var items: [String]
// [...] Do the stuff to get the items and add current input like before [...]
let destinationViewController = segue.destination as! ViewController2
destinationViewController.items = items
}
}
}
class ViewController2: UIViewController {
var items: [String]? // This is accessible from outside now
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(items) // We can now print this because it is set in prepareForSegue
}
}
I really hope I could help you with that and explained it understandable. Feel free to leave a comment if you have any questions.
You forget to write "let" or "var" in viewDidAppear. Try this:
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
let items = tempItems
}
}
If you want to use items after if statement, then you must declare variable before if statement:
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items: [String]
if let tempItems = itemsObject as? [String] {
items = tempItems
}
}

Getting objects from Parse into an Core Data via an Array

I have a tableview that gets it's data from Parse via a queryForTable function. This works fine. I would like to get the same objects from Parse and add them to an array that I can later store in Core Data! Does anyone know how to do this? I have added my code below to show how I add it to a TableView.
Thanks for the help in advance. ;)
//MARK: Query for Table with the details
override func queryForTable() -> PFQuery {
let discoveryQuery = PFQuery(className: "DiscoveryDetails")
discoveryQuery.cachePolicy = .NetworkElseCache
discoveryQuery.whereKey("discoveryID", equalTo: PFObject(withoutDataWithClassName: "Discovery", objectId: "\(varInDDT!.objectId!)"))
discoveryQuery.orderByDescending("createdAt")
return discoveryQuery
}
....
//I strangely cannot find the type to declare that will hold all the
values that are shown in cellForRowAtIndexPath. PFObject does not seem
to work either. Maybe there is something I am missing about the
objects type that's universal to all.
var objectsArray : [String] = []
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
//Discovery Items TableViewCell
var discoveryDetailItemsCell:DiscoveryDetailTableViewCell! = tableView.dequeueReusableCellWithIdentifier("DiscoveryDetailTableViewCell") as? DiscoveryDetailTableViewCell
if (discoveryDetailItemsCell == nil) {
tableView.registerNib(UINib(nibName: "DiscoveryDetailTableViewCell", bundle: nil), forCellReuseIdentifier:"DiscoveryDetailTableViewCell")
discoveryDetailItemsCell = tableView.dequeueReusableCellWithIdentifier("DiscoveryDetailTableViewCell") as? DiscoveryDetailTableViewCell
}
//Background Colour of the Cell
discoveryDetailItemsCell.titleLabel.text = object?.objectForKey("exerciseName") as? String
discoveryDetailItemsCell.titleLabel.textColor = UIColor.whiteColor()
discoveryDetailItemsCell.durationAndSetsLabel.text = "\((object?.objectForKey("durationOrSets"))!)"
discoveryDetailItemsCell.minAndSetLabel.text = "mins"
discoveryDetailItemsCell.distanceAndRepsLabel.text = "\((object?.objectForKey("distanceOrReps"))!)"
discoveryDetailItemsCell.kmAndRepsLabel.text = "km"
discoveryDetailItemsCell.weightLabel.text = "\((object?.objectForKey("weight"))!)"
discoveryDetailItemsCell.kgsLabel.text = ""
discoveryDetailItemsCell.dot1.textColor = UIColor.grayColor()
discoveryDetailItemsCell.dot2.textColor = UIColor.grayColor()
//Load Images
let backgroundImage = object?.objectForKey("workoutImage") as? PFFile
discoveryDetailItemsCell.backgroundImageView.layer.masksToBounds = true
discoveryDetailItemsCell.backgroundImageView.layer.cornerRadius = 8.0
discoveryDetailItemsCell.backgroundImageView.image = UIImage(named: "loadingImage")
discoveryDetailItemsCell.backgroundImageView.file = backgroundImage
discoveryDetailItemsCell.backgroundImageView.loadInBackground()
//My Attempt at adding one of the values into an array
objectsArray = [(object?.objectForKey("exerciseName"))! as! String]
return discoveryDetailItemsCell
}

Resources