[英]Access another view controller's property after an event
我有2個ViewController,第一個有一個數組,一旦ViewController出現,該數組就由獲取請求填充。 第二個ViewController有對該數組的引用。 但是,這是在填充之前引用一個空數組。
數組填充后,我想獲取參考。 這是一個片段。
class VC1: UIViewController {
let coreDataObjects = [NSManagedObject]() //At this moment, this array is empty
func viewWillAppear {
fetchRequestThatFillsTheArray() //Here, the array is filled
}
fetchRequestThatFillsTheArray() {
//calling NSFetchRequest
}
}
class VC2: UIViewController {
let vc1 = VC1()
vc1.coreDataObjects //Empty array
}
謝謝。
解決方法如下:
class VC1: UIViewController {
lazy var coreDataObjects = fetchRequestThatFillsTheArray()
func fetchRequestThatFillsTheArray() {
//calling NSFetchRequest
}
}
如果您仍然想要原始代碼的解決方案,或者在lazy
使用fetchRequestThatFillsTheArray()
遇到問題。 您必須使用NSNotification
。 閱讀通知編程主題
---請發表評論----
您應該稍微更改一下代碼。
class VC1: UIViewController {
lazy var coreDataObjects:[NSManagedObject] = self.fetchRequestThatFillsTheArray()
func fetchRequestThatFillsTheArray() -> [NSManagedObject] {
//calling NSFetchRequest
}
}
但是,由於在fetchRequestThatFillsTheArray()
使用了self.property
,因此無法使用此解決方案。
您必須使用NSNotification
。 這意味着您在fetchRequestThatFillsTheArray()
完成時發送通知。 並在vc2
注冊通知。 當vc2
收到通知時,它將執行所需的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.