1

Why in many fragment code declare instance variable like and for what? what different about property and non property

#import <Foundation/Foundation.h>

@interface class1:NSObject

{
   NSMutableString *currentData;
}
@property (nonatomic, retain) NSMutableString * currentData;
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nguyen Huu
  • 19
  • 3
  • That's old. No one should do that any more. Just declare the property. There is no longer any need to also declare the corresponding ivar. – rmaddy Sep 13 '13 at 03:07

1 Answers1

1

What you saw is an "old code"... but sometimes you still need to support old versions (e.g. 10.5).

A property is simply a couple of getter and setter (well.. it depends on the attributes you choose: e.g. readonly will generate only a getter). But a property operates (and so it needs) an instance variable. Usually what you see in the implementation file is something like

@implementation class1
@synthesize currentData = currentData;
@end

This means create getter and setter which uses currentData as variable.

For newer version you don't need to create the instance variable and you can just type the property and synthesize statement. In the most recent language version you don't even need the synthesize statement. Automatically an instance variable named _propertyName (underscore + name of the property) is created.

BTW: sometimes you still need to make your own getter and/or setter. Classic naming convention applies (e.g. - (void)setCurrentData: (NSMutableString*)newData; for setter and - (NSMutableString*)currentData; for getter), but same rules as before for properties: if you support only the most recent OSes you can just write the @property statement and right your getter and setter by using the "underscored" variable...

Francesco
  • 1,840
  • 19
  • 24