Arrays 使用不带分段的协议将数组从appDelegate传递到Viewcontroller

Arrays 使用不带分段的协议将数组从appDelegate传递到Viewcontroller,arrays,swift,userdefaults,Arrays,Swift,Userdefaults,我需要使用协议将数组从AppDelegate传递到viewcontroller。我对这个概念还不熟悉。请帮我写一些代码。我需要将字符串的dataArr传递给另一个viewcontroller,并将其显示在tableview guard let message = note(fromRegionIdentifier: region.identifier) else { return } window?.rootViewController?.showAlert(withTitle: nil, me

我需要使用协议将数组从
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")
}
let savedstring = UserDefaults.standard.array(forKey: "message")
cell?.cordinateLabel.text =  savedstring?[indexPath.row] as? String
return cell!
  • 使用协议
  • 先创建协议

    protocol MyDelegate {
         public yourMethod(param: String);
    }
    
    在ViewController中,您需要从协议扩展它,并将其设置为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);
    
  • 使用通知中心
  • 最简单的方法是使用NotificationCenter。 首先,您需要为通知添加扩展名。在应用程序中的任何位置命名。像

    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
       }
    
    现在,在您的应用程序委托中,甚至在应用程序的任何位置,您都可以通过发送通知调用viewController的方法,如

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

    使用notification center发送带有有效负载的通知“我需要使用协议将数组从AppDelegate传递到viewcontroller”Q1:任何与模型相关的数组在你的AppDelegate中做什么?问2:你需要协议做什么?我正在开发一个地理围栏应用程序。我正在从AppDelegate中的did接收通知委托方法接收警报。因此,我创建了一个数组并将警报发送到一个数组。我需要通过该数组在表视图中显示标识符列表。