Home Moving an object from one class to another in Swift
Reply: 1

Moving an object from one class to another in Swift

aaallleeexxx918 Published in 2017-11-14 18:09:25Z

there was a similar problem: There is an object addinAprel in the class ViewController, also there is a class SecondController, it is necessary to transfer this object from one class to another in Swift.

Example programs:

Function in the ViewController class:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("Selected item is", current_arr[row])
active_textField.text = current_arr[row]
let realm = try! Realm()
let events = realm.objects(EventsDB.self)

if ((text_field_months.text) == "Апрель")
    if ((text_field_days.text) == "8")
    let addinAprel=print(events.filter("dataMonth == %@ && dataDay ==%@",months_arr[3], days_arr[7]))
        print("very good")
        return addinAprel
    if ((text_field_days.text) == "1")
    let addinAprel=print(events.filter("dataMonth == %@ && dataDay ==%@",months_arr[3], days_arr[0]))
        print("very good")
        return addinAprel
    print("very bad")

Class SecondController:

import Foundation
import UIKit
import RealmSwift

class SecondController: UIViewController, UITableViewDelegate {
let realm = try! Realm()

override func viewDidLoad() {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You select \(massiv[indexPath.row])")

Oleh Zayats
Oleh Zayats Reply to 2017-11-14 18:45:29Z

It depends on the flow. There are multiple options like:

  1. Delegate pattern
  2. Notifications
  3. Passing via segue/unwind segue
  4. Passing via shared entity or service (Singleton for example)
  5. Referencing a ViewController directly
  6. Using storage (UserDefaults, databases etc.)

To answer the question you should provide more context.

From what I see you can use Option 5: Instantiate SecondController from ViewController (may keep it as a reference in class scope), set the property you want and present/push it. It's the most simple option.

I advise you to read about ViewControllers, Protocols/Delegation, Notifications more.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.294749 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO