推 steny138:我有問題的地方就是在 @synthesize image = _image; 06/17 09:02
→ steny138:不是已經預設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)
推 steny138:真的看懂了! 06/17 23:27
→ steny138:謝謝^_^ 06/17 23:29
推 tom19830924:我比較想問 為啥有些程式取值會不經由getter來取 06/19 00:06
→ tom19830924:也就是使用_xxx, 都經由self.xxx不是比較好?效能問題? 06/19 00:07
推 darktt:其實_xxx才是正確的寫法,當Property為readonly的時候 06/19 06:41
→ darktt:你就不能用self.xxx來寫入資訊 06/19 06:42
→ uranusjr:存取量大的時候用 property 效能還是有差 06/19 07:16
→ steny138:理論上 用getter的話 聽說會做好release的工作 06/19 13:05
→ steny138:好像是為了避免leak的產生 06/19 13:06
→ yuanruo:setter就會做好release的工作了~getter就單純返回值 06/19 14:25
→ yuanruo:為了避免循環引用~所以當值不同時setter就會release舊值 06/19 14:28
推 steny138:搜嘎 07/02 11:11