The Objective-C Programming Language
Encapsulating Data
1
2
3
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.
If you still need an instance variable, you’ll need to request that one be synthesized:
@synthesize property = _property;
1
2
3
It’s best practice to use a property on an object any time you need to keep track of a value or another object.
If you do need to define your own instance variables without declaring a property, you can add them inside braces at the top of the class interface or implementation, like this:
@interface SomeClass : NSObject {
NSString *_myNonPropertyInstanceVariable;
}
...
@end
@implementation SomeClass {
NSString *_anotherCustomInstanceVariable;
}
...
@end
@synthesize
1
You use the @synthesize directive to tell the compiler that it should synthesize the setter and/or getter methods for a property if you do not supply them within the @implementation block. The @synthesize directive also synthesizes an appropriate instance variable if it is not otherwise declared.
@synthesize firstName, lastName, age=yearsOld;
synthesize的作用:
- synthesize the setter and/or getter
- synthesizes an appropriate instance variable
因此手动提供setter和getter的实现可能回影响synthesize发挥作用
@dynamic
1
You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. It suppresses the warnings that the compiler would otherwise generate if it can’t find suitable implementations. You should use it only if you know that the methods will be available at runtime.
@interface MyClass : NSManagedObject
@property(nonatomic, retain) NSString *value;
@end
@implementation MyClass
@dynamic value;
@end