Re: [問題] Property的關係

看板MacDev作者 (←這人是超級笨蛋)時間12年前 (2013/06/17 16:08), 編輯推噓4(408)
留言12則, 5人參與, 最新討論串3/3 (看更多)
※ 引述《darktt (小朱)》之銘言:

06/17 09:02,
我有問題的地方就是在 @synthesize image = _image;
06/17 09:02

06/17 09:03,
不是已經預設image=_image 那怎麼不能用 image=XX
06/17 09:03
顯然你還是一整個沒搞懂... @interface Foo : NSObject { } @property (weak, nonatomic) UIImage *image; @end @implementation Foo @synthesize image = _image; @end 這個宣告大略等同於 @interface Foo : NSObject { UIImage *_image; } - (UIImage *)image; - (void)setImage:(UIImage *)newImage; @end @implementation Foo - (UIImage *)image { return _image; } - (void)setImage:(UIImage *)newImage { _image = newImage; } @end (實際上 implementation 產生的對等程式碼視 property 的各種參數會有不同, 這裡 的對等程式碼對應的 nonatomic, weak 只是最簡單的狀況) 仔細看看後面的那段, 根本沒有 image 這個變數 簡單的概念, 當你寫 @synthesize image = _image; 時, 前面那個 image 代表 property 的名稱, 後面的 _image 代表 instance variable 的名稱, 所以你只能 使用 self.image (在 Objective-C class 中等同於 [self image]) 或 _image, 不能用 image (因為根本沒有這個變數!) 這樣有懂了嗎... -- 我還是覺得 Objective-C 初學者應該要全力避免使用 property 和 dot-syntax 直到他們完全了解這兩個東西背後的意義為止 不然這兩個東西根本超容易搞爛改念讓人寫出無法言喻的程式碼... -- Les grandes et les meilleurs tone from "Zadok the Priest" Eine grosse stattliche Veranstaltung by F. Handel THE MAIN EVENT! These are the men Sie sind die Besten "Champions League" by Tony Britten THESE ARE THE CHAMPIONS! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.245.64.174 ※ 編輯: uranusjr 來自: 60.245.64.174 (06/17 16:08)

06/17 23:27, , 1F
真的看懂了!
06/17 23:27, 1F

06/17 23:29, , 2F
謝謝^_^
06/17 23:29, 2F

06/19 00:06, , 3F
我比較想問 為啥有些程式取值會不經由getter來取
06/19 00:06, 3F

06/19 00:07, , 4F
也就是使用_xxx, 都經由self.xxx不是比較好?效能問題?
06/19 00:07, 4F

06/19 06:41, , 5F
其實_xxx才是正確的寫法,當Property為readonly的時候
06/19 06:41, 5F

06/19 06:42, , 6F
你就不能用self.xxx來寫入資訊
06/19 06:42, 6F

06/19 07:16, , 7F
存取量大的時候用 property 效能還是有差
06/19 07:16, 7F

06/19 13:05, , 8F
理論上 用getter的話 聽說會做好release的工作
06/19 13:05, 8F

06/19 13:06, , 9F
好像是為了避免leak的產生
06/19 13:06, 9F

06/19 14:25, , 10F
setter就會做好release的工作了~getter就單純返回值
06/19 14:25, 10F

06/19 14:28, , 11F
為了避免循環引用~所以當值不同時setter就會release舊值
06/19 14:28, 11F

07/02 11:11, , 12F
搜嘎
07/02 11:11, 12F
文章代碼(AID): #1HliFvhE (MacDev)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):
文章代碼(AID): #1HliFvhE (MacDev)