在iOS開發(fā)中蠢涝,代理模式(protocol - delegate)是界面之間數(shù)據(jù)傳遞最為常見的一個設計模式
在Cocoa框架中也有大量使用阅懦,可以說是作為iOS開發(fā)者必備技能。
在我們OC開發(fā)時候使用delegate一般會把修飾符寫成weak惯吕,這樣在這個delegate實際的對象被釋放的時候怕午,會被置為nil,避免內存泄露诗轻。代碼大致如下:
@property (nonatomic, weak) id<MGIndexAdReusableViewDelegate> delegate;
那么一般寫過OC的童鞋去寫swift,也會照本宣科吏颖,也設置為weak,沒有錯半醉,但是事實情況會是怎樣呢 ?看如下代碼:
protocol TestDelegate {
func testMethod()
}
class TestClass {
weak var delegate: TestDelegate?
}
class ViewController: UIViewController, TestDelegate {
var testInstance: TestClass!
override func viewDidLoad() {
super.viewDidLoad()
testInstance = TestClass()
testInstance.delegate = self // error: 'weak' cannot be applied to non-class type 'TestDelegate'
}
func testMethod {
print("Test!")
}
}
上面注釋部分是報錯信息呆奕,為什么呢 衬吆?
這是因為swift中的protocol是可以被除class類型以外的struct type和enum type所遵守的,那么原因不言而喻了姆泻。struct type和enum type冒嫡,他們本身是不通過引用計數(shù)來管理內存的,所以也就不能使用weak來修飾孝凌,那么怎么辦呢 ?
方法有兩種
1.將protocol聲明為Objective - C的瓣赂,通過在protocol前面加@objc關鍵字來實現(xiàn)辜窑,這樣就只能由class來遵守了,代碼大致如下:
@objc protocol TestDelegate {
func testMethod()
}
2.在protocol的聲明后面加上class牙勘,這樣可以為編譯器顯式的指名這個protocol只能由class來遵守所禀,代碼大致如下:
// 更推薦這種方式,易于理解色徘,更能表現(xiàn)出問題的實質
protocol TestDelegate: class {
func testMethod()
}