从另一个视图控制器访问变量。 Swift

Access a variable from another view controller. Swift

如果有人向我发送消息并且我在特定的视图控制器 (ConversationViewController) 中,我会尝试显示通知。现在,我可以显示通知,但是当我尝试访问 ConversationViewController 中的变量 (otherProfileName) 时,它是零。我猜这是因为该变量 (otherProfileName) 是从另一个视图控制器传递过来的。我确定变量已成功传递。一切正常,可以显示通知并打印 "hi",但变量为零。有什么修复建议吗?

ConversationViewController

// passed from another view controller
var otherProfileName = String()

appDelegate

func application(application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    if application.applicationState == UIApplicationState.Active {
        print(topViewController())
        if topViewController() is ConversationViewController {
            let myCustomViewController: ConversationViewController = ConversationViewController(nibName: nil, bundle: nil)
            print(myCustomViewController.otherProfileName)
            print("HI")
            HDNotificationView.showNotificationViewWithImage(nil, title: "HI", message: "HHIHI", isAutoHide: true)
        }
    }
    completionHandler(UIBackgroundFetchResult.NewData)
}

func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
    if let MMDrawers = base as? MMDrawerController {
        for MMDrawer in MMDrawers.childViewControllers {
            return topViewController(MMDrawer)
        }
    }
    if let nav = base as? UINavigationController {
        return topViewController(nav.visibleViewController)
    }
    if let tab = base as? UITabBarController {
        if let selected = tab.selectedViewController {
            return topViewController(selected)
        }
    }
    if let presented = base?.presentedViewController {
        return topViewController(presented)
    }
    return base
}

这段代码没有意义:

    if topViewController() is ConversationViewController {
        let myCustomViewController: ConversationViewController = ConversationViewController(nibName: nil, bundle: nil)

翻译:

"If the top view controller is a ConversationViewController, create a new, empty instance of ConversationViewController, and ask that instance for it's otherProfileName value"

这就像在一组盒子中寻找蓝色盒子,因为您知道它包含一个苹果。当你找到一个蓝色盒子时,去建造一个新的空蓝色盒子,打开它,想知道为什么里面没有你的苹果。

您正在此处创建 ConversationViewController 的新实例

let myCustomViewController: ConversationViewController = ConversationViewController(nibName: nil, bundle: nil)

尝试

      if let myCustomViewController = topViewController() as? ConversationViewController {
            print(myCustomViewController.otherProfileName)
            print("HI")
            HDNotificationView.showNotificationViewWithImage(nil, title: "HI", message: "HHIHI", isAutoHide: true)
        }
     }