【问题标题】:pass an array from appDelegate to a Viewcontroller using a protocol without segues使用没有 segues 的协议将数组从 appDelegate 传递到 Viewcontroller
【发布时间】:2019-04-10 06:32:53
【问题描述】:

我需要使用协议将数组从AppDelegate 传递给viewcontroller。我对这个概念很陌生。请帮我一些代码。我需要将字符串的dataArr 传递给另一个viewcontroller 并在tableview 上显示它

guard let message = note(fromRegionIdentifier: region.identifier) else { return }
window?.rootViewController?.showAlert(withTitle: nil, message: "you have entered "  +  message)
if (dataArr.count <= 5){
    dataArr.append(message)
}

let userdefaults = UserDefaults.standard
userdefaults.set(dataArr, forKey: "message")
}

我只需要将这些警报保存到userdefaults 并在tableview 上显示它们我刚刚尝试过,但它只在tableview 上显示单个字符串

let savedstring = UserDefaults.standard.array(forKey: "message")
cell?.cordinateLabel.text =  savedstring?[indexPath.row] as? String
return cell!

【问题讨论】:

  • 使用通知中心发送带有payload的通知
  • “我需要使用协议将数组从 AppDelegate 传递给视图控制器” Q1: 什么是 any 模型-related 数组在您的应用程序委托中做什么? Q2:你需要a协议做什么?
  • 我正在开发一个地理围栏应用程序。我收到来自 AppDelegate 中的确实接收通知委托方法的警报。所以我创建了一个数组并将警报发送到一个数组。我需要通过该数组在表格视图中显示标识符列表。

标签: arrays swift userdefaults


【解决方案1】:
  1. 使用协议

首先创建协议

protocol MyDelegate {
     public yourMethod(param: String);
}

在您的 ViewController 中,您需要从 Protocol 扩展它,并将其设置为 AppDelegate

 class YourViewController: MyDelegate {
     // Your Other methods

     override func viewDidLoad() {
          super.viewDidLoad()

          // set your delegate to Appdelegate
          let appDelegate = UIApplication.shared.delegate as! AppDelegate
          appDelegate.yourDelegate = self;
     }


     func yourMethod(param: String) {
      // Do your stuff
     }
 }

现在最后在 AppDelegate 中声明协议对象并通过它的引用调用 yourMethod。

 class AppDelegate: UIApplicationDelegate {
     public yourDelegate: MyDelegate!;
 }

现在您可以在 AppDelegate 中的任何位置调用您的方法,例如

  yourDelegate.yourMethod(params);
  1. 使用通知中心

最简单的方法是使用 NotificationCenter。 首先,您需要在应用程序的任何位置向 Notification.Name 添加扩展名。喜欢

extension Notification.Name { static let mynotification = Notification.Name("mynotification") }

在你的视图控制器 viewDidLoad 方法中添加

NotificationCenter.default.addObserver(self, selector: #selector(yourMethod), name: NSNotification.Name.mynotification, object: nil)

然后在您的 ViewController 中添加一个在通知触发时将调用的方法

 func yourMethod(){
        //// do something
   }

现在在您的 App 委托中,甚至在应用程序的任何地方,您都可以通过发送通知 Like 来调用 viewController 的方法

 NotificationCenter.default.post(name: NSNotification.Name.mynotification, object: nil)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多