2014年6月5日 星期四

IOS Property,Instance variable 傻傻分不清楚

Programming with Objective-C --- Encapsulating Data --- You Can Implement Custom Accessor Methods



Note: The compiler will automatically synthesize an instance variable in all situations where it’s also synthesizing at least one accessor method. If you implement both a getter and a setter for a readwrite property, or a getter for a readonly property, the compiler will assume that you are taking control over the property implementation and won’t synthesize an instance variable automatically.



編譯器會自動合成你的property,如果你的R/W property 實作setter & getter,又或者你的R-Only property 實作了getter的話,編譯器會認為你已經做好property的控制,因此編譯器就不會幫你自動生成實體變數摟!!

如果你還是需要實體變數的話呢,你必須合成它
@synthesize property = _property;
難得找到OC的一些歷史,之前一直對Property和Instance variable分不清楚。
歷史:几个有用的Objective-C新特性

原來以前在宣告Property(name)的同時,還必須再宣告同名的Instance variable(_name),最後再使用synthesize把這兩者關聯在一起(@synthesize name = _name;)

現在只要宣告一行Property就全部搞定了

沒有留言:

張貼留言