将字符串从视图控制器传递到 Swift 中的文件

Passing string from view controller to file in Swift

在 swift 中,我想让用户在特定视图的 UITextView 中输入一个文本字符串,然后将该字符串传递到一个单独的文件,以便我可以对其进行操作。

在我的 PostViewController 文件中,我有

class PostViewController: UIViewController {

class var sharedPost: PostViewController {
    struct Static {
        static var instance: PostViewController?
        static var token: dispatch_once_t = 0
    }
    dispatch_once(&Static.token) {
        Static.instance = PostViewController()
    }
    return Static.instance!
}


@IBOutlet weak var postText: UITextView!

...

这将创建它的一个实例并将用户文本放入 postText 变量

在我要传递给它的文件中,我有

class Grade {
    let string = PostViewController.sharedPost
    var newString : String!

 ...

    init() {
        newString = self.string.postText.text

但是在输入时,程序崩溃并给我一个 "fatal error: unexpectedly found nil while unwrapping an Optional value"。这是否意味着它没有读取输入文本?我该怎么做才能解决这个问题?我也试过做 newString = self.string.postText?.text 但那也崩溃了。

PostViewController() 在您的 dispatch_once 中创建了一个新对象,但是,由于它不是显示的一部分,因此它的视图永远不会加载,因此它的 postText 出口不是填写。

假设您的应用创建了一个实际显示的 PostViewController,您需要获取对该应用的引用才能从文本视图中读取。

编辑:

一种方法是让 PostViewController 记住最近出现的实例(如果有的话)。

class PostViewController: UIViewController {

static var sharedPost: PostViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        PostViewController.sharedPost = self
    }

}

(我不确定 viewDidLoadviewWillAppear 中的作业是否更有意义。您可能想尝试一下。)


另一方面,我们似乎问错了问题并回答了错误的问题。

如果 PostViewController 在用户输入信息时更新 Grade 而不是 Grade 必须去钓鱼,这不是更有意义吗?