@property and @synthesize: why both?
I have been climbing the learning curve of X-code for about two months now. I understand the purpose of the @property/@synthesize directives, but it seems that it is a bit redundant to always declare the properties in the .h file, and then synthesize them in the .m file.
Why does the compiler need both direc开发者_如何学Gotives? If they are always used together, isn't one of them technically redundant?
Thanks in advance for any insights on this subject.
John Doner
The @property (...) foo
keyword is used inside your class definition.
You don't need to use @synthesize
keyword in the implementation file if you provide appropriate getters/setters
.
Example:
@property int SomeInt;
---
-(int)SomeInt {
return _someInt;
}
-(void)setSomeInt:(int)newValue {
_someInt = newValue;
}
Or you can use either @synthesize foo
to inform the compiler to generate getters/setters
for you or @dynamic
to inform the compiler that these methods will be available at runtime - both in the implementation file.
There's actually more magic behind properties in Objective-C, read up on them at Apple Reference Library.
It's so that you can split implementation and declaration. Seems pretty neat to me.
Well, you can't use @synthesize
in category implementations, so that might be one reason.
精彩评论