我有以下结构
Main ViewController:它负责调用(A)视图控制器。 (A)ViewController:创建一个CustomClass实例并具有该类的委托。 CustomClass:在每个1秒的时间段内,通过委托将消息发送到(A)视图控制器。
直到这里一切正常。一旦我返回到Main ViewController,委托就会保持活动状态,换句话说,委托更新A(ViewController)变量。我检查了(A)ViewController的viewDidDisappear被调用。 当我再次从Main ViewController返回到(A)ViewController时,会创建一个新的变量实例。无论如何,我不明白这一点。
除了这个疑问之外,我想了解当我返回主视图控制器时代表保持活着的原因。我正在使用UINavigationItem进行导航。
我是IOS开发的初学者。
谢谢高级!!!
编辑1: (A)ViewController由Segue从MainViewController调用。 segue是通过故事板添加的。
MainViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
AViewController.swift
class ScanDevices : UIViewController, CustomClassDelegate {
var myInts : [Int] = []
var customClass : CustomClass!
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
if customClass == nil {
customClass = CustomClass()
customClass.customClassDelegate = self
}
}
override func viewWillAppear(animated: Bool) {
print("viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
print("viewDidAppear")
}
override func viewWillDisappear(animated: Bool) {
print("viewWillDisappear")
}
override func viewDidDisappear(animated: Bool) {
print("viewDidDisappear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didDiscoverPeripheralInt(peripheral: Int) {
myInts.append(peripheral)
print("Number = \(myInts.count)")
}
}
CustomClass.swift
class CustomClass : NSObject {
var customClassDelegate : CustomClassDelegate?
// MARK: init
override init() {
super.init()
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "writeInt", userInfo: nil, repeats: true)
}
func writeInt () {
CustomClassDelegate?.didDiscoverPeripheralInt(3)
}
}
答案 0 :(得分:2)
var customClassDelegate : CustomClassDelegate?
您持有对您的委托的字符串引用。 它必须是
weak var customClassDelegate : CustomClassDelegate?
看看以下文件: http://krakendev.io/blog/weak-and-unowned-references-in-swift
答案 1 :(得分:0)
您的CustomClass
拥有对该代表的强烈引用。您必须使用weak
标记该属性:
weak var customClassDelegate : CustomClassDelegate?