Is it a good practice to declare properties in implementation file, If yes, what's the use?
Is following code, a good programming practice in objective-C ?
#import "Custom.h"
@interface Custom ()
@property (nonatomic, retain) UILabel *label;
@end
@implementation Custom
@synthesize label;
- 开发者_Python百科(void) dealloc {
[label release];
[super dealloc];
}
@end
The idea behind this is that all properties you declare in your header file, are visible and accesible for everyone outside that class. To respect the encapsulation principle of OOP, you want to make the scope of certain members of your class as private as possible. So all those members that only your class will use, should be hidden to "the outside world". This can be done by declaring a special type of category called "extension" (it can't have a name, it's declared as @interface Class () ), and the properties inside that extension (along with private method declaration if you want as well)
As to the question whether it's a good practice, that may be discussed among different developers. To me, it is since it's good OOP practice, and also because it helps keeping your header file as clean as possible (and so making it easier for other developers to see what "services" your class provides)
I like to do this to create private interfaces. If a property is only used in your implementation, not in collaboration with other objects, it should not pollute the header (which defines the public interface). You can also hide private protocol implementations this way:
@interface YourClass () <UIAlertViewDelegate>
This way the users of your class don’t have to know that you have an UIAlertView
buried somewhere in your implementation.
What could be considered a downside is that your subclasses can no longer access the “private” properties. You have to either move their declaration to the header file (making them public), or create a special “protected” header.
Another option worth mentioning in this context is declaring private variables in the @implementation
directive:
@implementation YourClass {
NSString *foo;
NSUInteger bar;
}
These are not statics, they are regular instance variables.
You would want to define label
in your header for later use through out other methods in your @implementations
. For example, create that label in your viewDidLoad
, and you can change it throughout the other methods..
精彩评论