閱讀471 返回首頁    go 阿裏雲 go 技術社區[雲棲]


iOS自學筆記--outlet, @property

照貓畫虎一兩個程序後。也就是畫了幾個控件,可能會對例子中的一些陌生玩意兒產生疑惑,比如,什麼是outlet.

什麼是outlet?

Apress的書有這麼一句話:

Absolutely right. Our controller class can refer to objects in the nib file by using a special kind of instance variable called an outlet. Think of an outlet as a pointer that points to an object within the nib. For example, suppose you created a text label in Interface Builder and wanted to change the label’s text from within your code. By declaring an outlet and connecting that outlet to the label object, you could use the outlet from within your code to change the text displayed by the label.

outlet是個特殊的類成員變量,可以看成是指針,指向一個nib中的對象。

說俗點就是,你畫出來一個text label. 假設想用代碼來編輯這個label控件。你需要聲明一個outlet然後和這個label控件的對象(object) 聯係起來(指針)。

Apple的文檔中稱:

IBOutlet is a special keyword that is used only to tell Xcode to treat the object as an outlet. It’s actually defined as nothing so it has no effect at compile time.

其實也就是說,IBOutlet其實隻是告訴Xcode,讓Interface builder(就是拖控件的環境)知道某個對象是指向某個控件的。編譯期間壓根沒用。


最後的總結就是,outlet隻是用來告訴Xcode某個指針變量指向畫出來的某個控件,然後在代碼中使用那個指針來操作那個控件。


什麼是 @property?

一會兒看書,一會兒又看Apple的文檔,會發現有很多不一樣的地方。這很正常,技術在更新,標準在變化。比如最新的apple的文檔(基於iOS 5)的,從來不定義類變量(instant variables)。隻是在@end前定義一個@property。而很多書中的例子還在定義instant variable(比如Apress的iPhone 4開發)

@property(頭文件中) 是用來和@synthesize(源文件中) 一起告訴編譯器(compiler)在編譯的時候自動生成getter和setter方法,省事兒用的。

其實Objective-C 2.0 建議大家隻使用@property忽略類成員變量的定義。 然而,這取決於具體運行環境(老版本可能不太支持,具體不管了,反正搞明白問啥有的隻用@property有的同時聲明類成員變量就行了)。

最後更新:2017-04-02 22:15:46

  上一篇:go 服務器RAID技術方案你知多少?
  下一篇:go IBM Key Management工具(iKeyMan)腳本吃掉%*$*無法接收命令行參數之解