Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to declare properties in implementation file, If yes, what's the use?

Tags:

ios

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;

  - (void) dealloc {
      [label release];
      [super dealloc];
  }

  @end
like image 213
Soni Avatar asked Sep 08 '11 06:09

Soni


2 Answers

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)

like image 174
Javier Soto Avatar answered Nov 19 '22 16:11

Javier Soto


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.

like image 35
zoul Avatar answered Nov 19 '22 15:11

zoul